Category Archives: Penetration Testing

Offensive Tools and Techniques

In this article I go over a series of examples that illustrate different tools and techniques that are often used by both sides of the force! To exemplify it, I will follow the different attack stages and will use the intrusion kill chain as methodology. This methodology consist of seven stages. Reconnaissance, weaponization, delivery, exploitation, installation, C2 and action on objectives.

offensive-logoLet’s start with Recon! The goal here is to seek information about the target, normally a person. Targeting high profile individuals might be difficult because these individuals tend to have a personalized security group that looks after them. However, using different intelligence-gathering techniques such as searching information available in a variety of public information sources you can target other personnel. Due to the human nature, people succumb to social engineering techniques and several times they provide more information than is necessary. A starting point is to harvest metadata about the organization and personnel. Normally, companies do not know what metadata they are giving way. Metadata is a golden pot of information and information such as usernames, software versions, printers, email addresses and others can be retrieved using a tool such as FOCA Metadata Analysis Tool. You can see the presentation that was given by Chema Alonso and Jose Palazon Palatko in 2010 at Defcon 18 about FOCA 2.5.  At the end the attacker will use whatever works to gather as much information as possible about employee names, position in the hierarchy, friends and relatives, hobbies, etc.

Next step, weaponization and delivery! After getting as much information as possible and performing enough recon the attacker will choose the best method to perform the attack with his available resources. Nowadays, spear phishing techniques with attached documents are very dominant and probably a good choice as attack vector. The sophistication of how a document is weaponized and delivered might correlate with the amount of resources available to the attacker. In the example below I show how you could use Metasploit to easily create a word document with a malicious macro that when executed will connect back to the attacker system and establish a command and control channel. The payload uses HTTPS as communication channel but it uses a self-signed certificate and points to an IP address and not a domain. In organization of different sizes, many times the web filtering controls are tight and use different blocking techniques that might detect and stop this type of connection. However, the attacker can register a new domain or buy an expired domain ahead of time, create a simple and realistic web page and categorize the domain in a category such as Finance or Healthcare – these are normally allowed in web filtering products and probably the SSL wouldn’t be terminated and inspected. In addition, the attacker can buy a cheap SSL certificate and make this scenario much more realistic.  In addition, Metasploit just introduced an updated traffic obfuscation technique that will make harder for security products to detect it.

Before I continue with the different tools and techniques, is worth to mention that in this article I give several examples using the Metasploit Framework. For those of you who don’t know, Metasploit framework was originally created by the legendary H.D. Moore back in 2003. Originally coded in Perl and then ported to Ruby. In 2004, Metasploit Framework 2.0 was released and had less than 20 exploits and a similar number of payloads. Today, the free version of Metasploit framework has more than 1600 exploits and more than 400 payloads. In addition many other auxiliary modules, encoders and post exploitation modules are available. The modular framework of Metasploit makes it a fantastic tool to design, build and launch exploits.

So, the picture below illustrates how to use Metasploit to create a weaponized Word document. An alternative to this technique is to use PowerShell Empire. See this article from Matt Nelson.

offensive-macro

Then, the word document can be customized and tailored to the target. To summarize, the attacker crafts a phishing email, either with a weaponized document or malicious link. This coupled with different social engineering techniques that appeal to human nature and exploit human vulnerabilities have good probability to make the attack a success. There is other factor that might impact the success of the campaign, which is the ability of the malicious email/link to circumvent the multitude of expensive filters that are layered throughout the network boundary and reach to the endpoint. If the email reaches the endpoint, you might have a well-intentioned employee making mistakes.  If these conditions are met, the attacker will establish a foothold inside the corporate network.

The picture below depicts the steps performed by the attacker to launch the Metasploit handler that will accept the beacon from the malicious document. Then, it shows the communication received and the established session.

offensive-macrohandler

Next step exploitation! With a foothold in the environment and an established communication channel the attacker will act quickly, stealthy and will probably try to find avenues to exploit other systems and achieve higher privileges.  Ruben Boonen who maintains fuzzysecurity.com and goes by the handler @FuzzySec has wrote a very comprehensive article where he describes the different techniques that could be used to escalate privileges on a Windows environment. Another great resource is the paper “Windows Services – All roads lead to SYSTEM” from Kostas Lintovois that exemplifies several ways in which misconfigured services could be compromised.  These techniques are very useful for attackers because in many organizations normal users don’t have admin rights. Admin rights are likely a goal that all attackers aim in an enterprise environment because it facilitates their job.

Many of the techniques written by Ruben and others have been materialized in the post-exploitation framework known as PowerSploit in a module called PowerUp.ps1 which has been originally written by Will Schroeder – a brilliant security researcher that in recent years released powerful tools -. PowerSploit contains a great library of modules and scripts that help in all phases of an attack life-cycle.  The PowerUp module facilitates the discovery of conditions that would allow an attacker to execute a technique that will lead him to get a privileged account. All this done using PowerShell and can be executed from within Meterpreter using the PowerShell extension that was written by OJ Reeves and incorporated into Metasploit  This means, that attacker can run PowerUp from within Metasploit. You can read more about PowerUp on Will Schroeder blog and also get PowerUp cheat sheet from here.

The picture below illustrates this scenario, where the attacker after getting a foothold in the environment – via phishing email – verifies that the account he is operating with doesn’t have enough privileges to run additional modules such as the powerful Mimikatz. Mimikatz is a post-exploitation tool written in C and developed by Benjamin Delphy. You can read more about many of its features on Sean Metcalf Unofficial Guide to Mimikatz and Command reference here and here. However, Meterpreter contains a PowerShell module that would allow the attacker to execute PowerShell commands. In this case the attacker can load the PowerShell module, execute the necessary commands to download the PowerUp from GitHub, a site owned by the attacker or other place and then perform the Invoke-AllChecks. At the time of this writing, the PowerUp module contains 14 checks.

offensive-powerup

In this case, as you could see in the image, the conditions necessary to perform DLL hijacking are found by PowerUp module. Essentially, the system contains a directory that any authenticated user can write to and this directory is part of the %PATH% environment variable. With this the attacker can leverage the DLL search order and obtain system privileges.  In this case PowerUp suggests to use “wlbsctrl.dll”. For this to work the Windows service “IKE and AuthIP IPsec Keying Modules” needs to be running but in enterprises where workstations have VPN clients installed this is quite common. This vulnerability was discovered in 2012 by the High-Tech Bridge Security Research Lab. It leverages the Windows service “IKE and AuthIP IPsec Keying Modules”, which during startup tries to load the “wlbsctrl.dll” DLL that doesn’t exist on default Windows installations. A great explanation about how this technique works and why the vulnerability exists was written by Parvez Anwar here.  Another resource about this topic is “DLL Hijacking Like a Boss!” presentation Jake Williams and an old article from the Corelan team here.

So, now that there is an avenue to explore, the next step is for the attacker to create a DLL that matches the architecture of the target system and has the name “wlbsctrl.dll”. This can be easily done with msfvenom. This utility is very popular to create one liners commands that will generate and encode a desired payload. Msfvenom was added to Metasploit in 2011 and combines the older Msfpayload and Msfencode commands in one utility. This is showing in the figure below.

offensive-dll

Another way to leverage this technique is to use Write-HijackDll function available in the PowerUp.ps1 module. This function will create and drop the “wlbsctrl.dll” DLL into the writable path and when the service starts the DLL will load and will add a user to local administrators with a predefined password.

An important remark in regards to the usage of PowerShell is that on some environments the security might be tight and PowerShell execution might be blocked. However, in this cases the attacker could use other techniques and use other tools such as PowerOPS: PowerShell for Offensive Operations tool written by Portuculis Lab and inspired in the PowerShell Runspace Post Exploitation Toolkit written by Cn33liz.

After that, the attacker uploads the DLL to the desired folder, the attacker can force a reboot or wait for the system to be rebooted. When the system starts, the IKEEXT service will be started and the malicious DLL will be loaded, spawning a command and control channel back to the system owned by the attacker and with SYSTEM privileges. The picture below illustrates the upload of the malicious DLL to the folder that has weak permissions and is part of the %PATH% variable. Then it follows the command and control channel that is established due to the IKEEXT service being started. Due to the high privileges the attacker can then move on and start using the powerful Mimikatz module. To start he can obtain clear text credentials by using Kerberos command.

offensive-dllhijack

Now, the attacker is operating under a high privileged account! With that, the attacker can move on and find a way to establish a persistence mechanism and in parallel move laterally within the environment.

Next step, installation and C2! There are a multitude of clever techniques and tools used by attackers to accomplish a persistence mechanism but in this case I would give an example of using WMI combined with PowerShell using a payload crafted by Metasploit.

WMI has gained popularity among attacker in recent years. A good resource is the presentation that Matt Graeber gave on BlackHat 15 : Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asynchronous, and Fileless Backdoor. In addition, William Ballenthin, Matt Graeber and Claudiu Teodorescu have written a great paper about the usage of WMI for both offense and defense. Furthermore, you can read the paper WMI for Detection and Response from NCCIC/ICS-CERT.

So, to achieve persistence the attacker could use Windows Management Instrumentation (WMI). The WMI will be used as a vehicle to trigger a payload to run at a particular event. This event could be a specific schedule, an event that occurred at the OS level, such as login or one of the many events supported by WMI. The payload would leverage PowerShell to perform a technique known as Reflective DLL injection which will call back to the attacker system and inject the Metasploit Meterpreter – to read more about Reflective DLL injection read this article from Dan Staples and its references -. The communication occurs over HTTPS back to the domain owned by the attacker. In sum, the attacker will only use windows built-in functionality combined with Metasploit. This arrangement of different tools and techniques lead to more powerful attacks that are harder to detect. In addition this technique leverages in memory payload that doesn’t touch disk due to the fact that uses a PE loader in memory to load the DLL and not the traditional LoadLibraryA() method. The persistence mechanism is inside the WMI repository which is likely to be outside of the radar of many defenders.

Let’s see how the attacker can build this. To craft the payload the attacker could use msfvenom utility that is part of Metasploit framework. The following picture illustrates the use of msfvenom to create the Reflective DLL injection payload using PowerShell format.

offensive-pshcmd

Next step would be to weaponize this payload into a Managed Object Format (MOF) script.

offensive-wmimof

Next the attacker will use the Managed Object Format (MOF) compiler, Mofcomp.exe on the target machine. This utility will parse a file containing MOF statements and adds the classes and class instances defined in the file to the WMI repository. A good article about MOF is “Playing with MOF files on Windows, for fun & profit” from Jérémy Brun-Nouvion. After that, a series of wmic.exe commands can be executed to view the contents of the different classes.

offensive-wmicommands

These commands are executed within the Meterpreter session that was established with the DLL hijacking technique. Then the attacker can cover his tracks and delete the malicious MOF script and move on. When the WMI event is triggered, the payload is invoked and a meterpreter session is established back to the system owned by the attacker. With this, the attacker has a persistence mechanism and is operating in the target environment with a privileged account.

Next, action on objectives! Lateral movement has been traditionally done using a variety of commands and tools such as net.exe, psexec.exe and wmic.exe. Nowadays, you can add PowerShell to the mix.. More specifically using the PowerView tool which was developed by William Schroeder and is part of PowerSploit tools and scripts. PowerView is an advanced active directory enumeration tool written in PowerShell that allows an attacker to gather extensive amount of information about a Windows enterprise environment. You can read more about the reason behind Powerview hereThis great write-up demonstrates several use cases for PowerView. Once again, we can load PowerView from within our Meterpreter sessions. In this case, the session has SYSTEM privileges and was obtained leveraging the WMI persistence but PowerView can run with a normal account.  The picture below exemplifies this step.

offensive-powerview

The list of functions available within PowerView is here and the cheat sheet here. The attacker starts enumerating different aspects of the Active Directory and the different systems just by leveraging PowerShell commands. To perform this he can leverage different techniques and modules within PowerView.  For a great summary you can see – once again – William Schroeder presentation given at Troopers 16 entitled “I have the power view”.

So, to start, the attacker can leverage the Kerberoasting technique. This technique pioneered by Tim Medin – I recommend you watch his presentation “Attacking Kerberos – Kicking the Guard God of Hades” – is brilliant and exploits the way Kerberos functions inside a Microsoft environment. This technique has been reorganized and adopted by PowerView and to run it is as simple as to list all user accounts in the active directory environment that have a SPN, request a Kerberos ticket and extract the crypto material. Then crack it offline to obtain clear text password. You can read more about it in this two articles written by William here and here. The below picture illustrates the Kerberoasting technique.

offensive-kerberoast

After obtaining the hash you could use John the Ripper to crack the password using as hash format the krb5tgs.

Another attack vector is to find accounts in the Active Directory that don’t require Kerberos preauthentication i.e., the PreAuthNotRequire attribute is enabled. This technique was pioneered by Geoff Janjua from Exumbra Operations and you can read the work he did in the article “Kerberos Party Tricks: Weaponizing Kerberos Protocol Flaws“. Essentially the technique consists on listing all accounts that have this attribute and request a Kerberos ticket for those accounts. This ticket contains crypto material that can be extracted and cracked offline. Once again this technique was adopted by PowerView and you can read more about it here.

Finally, if these techniques don’t work, then the attacker likely will move from system to system until he finds a system where he can obtain administrative privileges and move on until he finds a domain admin. This can be daunting task in large environments but once again William Schroeder coded the necessary steps into a series of PowerView modules that are coined with the Hunter word such as Invoke-UserHunter, Invoke-StealthUserHunter and many others that will facilitate the search for high value targets. You can view his presentation “I hunt sysadmins” to understand more what these modules do behind the scenes.  Justin Warner, one of the founders of PowerShell Empire, wrote a great article explaining how these modules works and went further by explaining a technique he named as derivative local admin. This technique was then automated by Andy Robbins which started in a proof-of-concept tool called PowerPath which leverages algorithms that are used to find the shortest path between two points. Andy then worked with Rohan Vazarkar and Will Schroeder  and their work culminated in the release of a tool called BloodHound. The tool was released as open source tool at DEF CON 24. Bottom line, using the different techniques and tools implemented by these brilliant folks the threat actor is likely to succeed obtaining a high privileged account.

Then, is matter of pivoting inside the enterprise environment using the obtained privileged accounts. For that the attacker can leverage the netsh.exe port forwarding feature or the Meterpreter port proxy command to pivot between internal systems. This technique is commonly used by attackers that want to use an internal system as pivot, allowing direct access to machines otherwise inaccessible from the attacking system. The command in the picture below illustrates this, where after configuring the port forwarding on the compromised system, the attacker can use wmic.exe to launch PowerShell on a remote system that will connect back to the attacker system and establish a meterpreter session.

offensive-wmimove

From this moment, its a cycle. Enumerate weakness, exploit them, compromise the system, move further, repeat. This cycle goes on and on until the attacker meets his objectives. A great resource about the techniques that were shown and many others are listed in this article written by Raphael Mudge, the author of Cobalt Strike.

That’s it. With this we covered different tools and techniques that are used in the different attack stages and used nowadays by security professionals but as well by cyber criminals and APT groups. After this, I would ask, how would you detect, prevent and respond to each one of the steps outlined in this attack scenario?

Feel free to share your ideas in the comments below. Thanks for reading!

Tagged , , , , , , , , ,

The ABC’s of a Cyber Intrusion

IntrusionNowadays, in corporations of any size and maturity level, I believe the success of many of the initial compromise and follow up actions is based on three variables. First, a well-crafted phishing email, either with a weaponized document or malicious link. Second the ability of the malicious email/link to circumvent the multitude of expensive filters that are layered throughout the network boundary and reach to the endpoint. Third, a well-intentioned employee making mistakes.  If these three conditions are met then the threat actor is likely to establish a foothold inside the corporate network.  Of course the conditions for the second and third variable to be met are likely outside of the attacker control and depends on many factors that can impact the success of the exercise. For example, two questions that might be relevant to determine how hard would be for a threat actor to get in, are: How well optimized, tuned and monitored is the deployed security technology? How well behaved and trained are the corporate users about the different types of threats?

Nevertheless, a threat actor that has strong technical capabilities can shift tactics and compromise websites that are related to your business and instead focus on a watering hole attack. This might remove the third variable from the equation.

Once the threat actor(s) got in, he will likely perform internal recon to find assets and data of interest. To collect this information he needs a toolbox. More often than the defenders would like the attackers are using Windows native tools to perform their actions. However, many times to be able to access more resources within the environment they deploy their own tools which sometimes are legitimate sysadmin tools – like SysInternals Suite. Normally, these tools are moved into the environment using the same channel that has been used to establish foothold. The toolbox might consist in exploit(s), credential theft tool(s), utilities to (de)compress and encrypt data and other utilities or scripts.

After having their toolbox deployed – normally referred as staging phase – is common that they start enumerating and mapping the environment. The initial collection might consist of information about the users, their roles, the enforced password policies, the workstations and server names. To do this the threat actor only needs to query the Domain. By Domain I mean the Active Directory which is likely present in any corporate network environment. In a very simple manner the Active Directory is a directory that can be easily queried just like someone would query any other directory such as the yellow pages. Just by executing the net.exe command on a command prompt the attacker can dump all the users, service accounts and which users and service accounts belong to which groups. This information is of great value and become very useful when the attacker is moving laterally. In addition, this information can be complemented by gathering which users are logged on a particular system using the query.exe command. Furthermore, the attacker can leverage powerful Windows Management Instrumentation Command Line (wmi.exe) and PowerShell techniques to increase his capabilities to collect even more information about the Domain. This can all be done with a non-privileged account.

Then, provided with all this rich information the threat actor can start expanding his territory and move laterally. How would he do that? Well, in fact you could be thinking about using the latest 0-day or a novel exploit technique but in today’s corporate networks sometimes the attacker doesn’t need this. Why? Well, many times the weakness of corporate networks is processes and people. For example, the persons that have the keys to the domain such as sysadmins are likely to be a target. The sysadmins are persons with a day job, a pile of tasks to perform and many times part of an understaffed team. Moreover, their goal is likely not security but availability of the services, minimum disruption to the business and at the end of the day a job well done that satisfy the business needs.

Consider the scenario that exists in most corporate networks when someone raises a ticket into helpdesk. Or some endpoint maintenance or action needs to be performed by a sysadmin. Many times the administration of the workstations is done by sysadmins that connect to the endpoint and authenticate using domain credentials that have privileged accounts. This will make their credentials exposed because when the user logs on interactively, Windows will cache the user password in memory. Perhaps, here we have a problem with the processes and not with technology. A privileged domain account should never login into a workstation. Other scenario that is problematic is the management of service accounts. Many times privileged service accounts are used for all type of services. This means the credentials of the service accounts are exposed and can be retrieved by an attacker with local access to the system. Therefore, service accounts should be managed prudently and more important a common mistake is to allow service accounts to login interactively. The scope of service accounts should be limited and, perhaps, here we have another process issue, service accounts should never be used to logon interactively. Another common challenge is that internal network segregation is often not the same as the perimeter leaving services and servers exposed to direct access from the workstations. These are some of the common challenges that are difficult problems to solve and where many times convenience wins and technology alone is not likely to overcome.

What is the impact of this? If a threat actor manages to get a foothold inside an environment that relies on practices such as the ones described previously, then he can access a variety of credentials. The captured credentials will depend on the technique and hardening settings of the endpoint used and are either in a form of a hash, ticket or clear text. This can be accomplished using tools such as Windows Credential Editor, Mimikatz, Gsecdump or AceHash. Won’t antivirus detect these tools? Likely, when they are used off the shelf but not when they are customized. Furthermore, more often than we would like, the internal network segregation is simple and not designed to prevent attacks. This means the attacker can enumerate services at will and leverage the gathered credentials to logon into servers. This step is a game changer!

If the attacker has credentials that can be used to login into your Servers and Domain Controllers then is likely game over. For example he could create a persistence and unnoticed backdoor just by setting a registry key that will use the cmd.exe as a Debugger for tools like sethc.exe (Sticky Keys) and osk.exe (On-screen keyboard). Or even worse he could easily steal the Active Directory database (ntds.dit). Even though the database is not accessible via user mode API’s the threat actor can leverage different techniques such as Volume Shadow copy, Powershell offensive framework like PowerSploit or use a forensic tool that is able to read low level NTFS. With a copy of the Active Directory database the threat actor can perform an offline attack using tools like Impacket secredumps to extract all the credentials. If the threat actors have the keys to the kingdom they will likely be undetected for quite some time and might start using the same egress points as your remote access users. How many VPN users do you have that are in the exception list of not having 2nd factor?

From an IT point of view this will mean your network would be in the worst state possible and your most plausible solution, among other things, is to rebuild the workstations, servers and potentially go over the painful task of having to rebuild the entire Active Directory forest. Now, this will be expensive however, it’s not impossible and the organization will survive. But, if the attacker also gets access to the servers that hold the organization critical information, valuable data, and intellectual property that would make the business leaders tremble. The financial direct or indirect losses of a security incident can be significant. The reputational damage can be difficult to assess and the disruption of critical systems on heavy regulated industry can have significant consequences.

Multi-stage, multi-faceted attacks are here to stay. The tools and technique will evolve and become more sophisticated than ever. The threat actors behind the attacks will try to become stealthy and remain under the radar.  However, on the other side of the fence we have the defenders. Which I believe can have a big impact on detecting and preventing the threat actors mission. If the detection only occurs after the fact then they can respond and stop the bleeding and limit the damage. But before they do this the organizations should get the basics right. It can take time and is never too late. A good starting point is to choose a framework such as the SANS TOP 20 Critical Controls. Use it as a reference for building, designing, deploying and adopt security controls and measure the security posture of your organization. Then move on from there to build more advanced capabilities!

Tagged , , ,

Evolution of Stack Based Buffer Overflows

overflowOn the 2nd November, 1988 the Morris Worm was the first blended threat affecting multiple systems on the Internet.  One of the things the worm did was to exploit a buffer overflow against the fingerd daemon due to the usage of gets() library function. In this particular case the fingerd program had a 512-byte buffer for gets(). However, this function would not verify if the input received was bigger than the allocated buffer i.e., would not perform boundary checking. Due to this, Morris was able to craft an exploit of 536-bytes which will fill the gets() buffer and overwrite parts of the stack. More precisely it overwrote the memory address of the return stack frame with a new address. This new address would point into the stack where the crafted input has been stored. The shellcode consisted on a series of opcodes that would perform the execve(“/bin/sh”,0,0) system call. This would give a shell prompt to the attacker. A detailed analysis about it was written by the Eugene Spafford, an American professor of computer science at Purdue University. This was a big event and made buffer overflows gain notoriety.

Time has passed and the security community had to wait for information about the closely guarded technique to be publicly available.  One of the first articles on how to exploit buffer overflows was written in the fall of 1995 by Peiter Zatko a.k.a Mudge – at the time Mudge was one of the members of the prominent hacker group L0pht.  One year later, in the summer of 1996, the 49th issue of the Phrack e-zine was published. With it, came the notorious step-by-step article “Smashing the Stack for Fun and Profit” written by Elias Levy a.k.a. Aleph1.  This article is still today a reference for the academia and for the industry in order to understand buffer overflows.  In addition to these two articles another one was written in 1997 by Nathan Smith named ” Stack Smashing vulnerabilities in the UNIX Operating System.” These 3 articles, especially the article from Aleph1 allowed the security community to learn and understand the techniques needed to perform such attacks.

Meanwhile, in April 1997 Alexander Peslyak a.k.a. Solar Designer posted on Bugtraq mailling list a Linux patch in order to defeat this kind of attacks. His work consisted in changing the memory permissions of the stack to read and write instead of read, write and execute. This would defeat buffer overflows where the malicious code would reside in the stack and would need to be executed from there.

Nonetheless, Alexander went further and in August 1997 he was the first to demonstrate how to get around a non-executable stack using a technique known as return-to-libc. Essentially, when executing a buffer overflow the limits of the original buffer will be exceeded by the malicious input and the adjacent memory will be overwritten, especially the return stack frame address. The return stack frame address is overwritten with a new address. This new address, instead of pointing to an address on the stack it will point to a memory address occupied by the libc library e.g, system().  Libc is the C library that contains all the system functions on Linux such as printf(), system() and exit().  This is an ingenious technique which bypasses non-executable stack and doesn’t need shellcode.  This technique can be achieved in three steps. As Linus Torvalds wrote in 1998 you do something like this:

  • Overflow the buffer on the stack, so that the return value is overwritten by a pointer to the “system()” library function.
  • The next four bytes are crap (a “return pointer” for the system call, which you don’t care about)
  • The next four bytes are a pointer to some random place in the shared library again that contains the string “/bin/sh” (and yes, just do a strings on the thing and you’ll find it).

Apart of pioneering the demonstration of this technique, Alexander also improved his previous non-executable stack patch with a technique called ASCII Armoring. ASCII Armoring would make buffer overflows more difficult to happen because it will map the shared libraries on memory address that contain a zero byte such as 0xb7e39d00.  This was another clever defense because one of the causes of buffer overflows is the way the C language handles string routines like strcp(), gets() and many others. These routines are created to handle strings that terminate with a null byte i.e, a NULL character. So, you as an attacker when you are crafting your malicious payload you could provide malicious input that does not contain NULL character. This will be processed by the string handling routine with catastrophic consequences because it does not know where to stop.  By introducing this null byte into memory addresses the payload of buffer overflows that are processed by the string handling routines will break.

Based on the work from Alexander Peslyak, Rafal Wojtczuk a.k.a. Nergal, wrote in January 1998 to the Bugtraq mailing list another way to perform return-to-libc attacks in order to defeat the non-executable stack. This new technique presented a method that was not confined to return to system() libc  and could use other functions such as strcpy() and chain them together.

Meanwhile, In October 1999, Taeh Oh wrote “Advanced Buffer Overflow Exploits” describing novel techniques to create shellcode that could be used to exploit buffer overflow attack.

Following all this activity, Crispin Cowan presented on the 7th USENIX Security Symposium on January 1998 a technology known as StackGuard. StackGuard was a compiler extension that introduced the concept of “canaries”. In order to prevent buffer overflows, binaries compiled with this technology will have a special value that is created during the function epilogue and pushed into the stack next to the address of the return stack frame. This special value is referred as the canary. When preforming the prologue of a function call, StackGuard will check if the address of the return stack frame has been preserved. In case the address has been altered the execution of the program will be terminated.

As always in the never ending cat and mice game of the security industry, after this new security technique was introduced, others have had to innovate and take it to the next level in order to circumvent the implemented measures.  The first information about bypassing the StackGuard was discovered in November 1999 by the Polish hacker Mariusz Wołoszyn and posted on the BugTraq mailing list. Following that In January 2000, Mariuz a.k.a. Kil3r and Bulba, published on Phrack 56 the article “Bypassing StackGuard and StackShield”.  Following that a step forward was made in 2002 by Gerardo Richarte from CORE security who wrote the paper “Four different tricks to bypass StackShield and StackGuard protection”.

The non-executable stack patch developed by Alexander was not adopted by all Linux distributions and the industry had to until the year 2000 for something to be adopted more widely.  In August 2000, the PaX team (now part of GR-security) released a protection mechanism known as Page-eXec (PaX) that would make some areas of the process address space not executable i.e., the stack and the heap by changing the way memory paging is done.  This mitigation technique is nowadays standard in the GNU Compiler Collection (GCC) and can be turned off with the flag “-z execstack”.

Then in 2001, the PaX team implemented and released another mechanism known as Address Space Layout Randomization (ASLR). This method defeats the predictability of addresses in virtual memory. ASLR randomly arranges the virtual memory layout for a process. With this the addresses of shared libraries and the location of the stack and heap are randomized. This will make return-to-libc attacks more difficult because the address of the C libraries such as system() cannot be determined in advance.

By 2001, the Linux Kernel had two measures to protect against unwarranted code execution. The non-executable stack and ASLR. Nonetheless, Mariusz Wołoszyn wrote a breakthrough paper in issue 58 of Phrack on December 2001.  The article was called “The Advanced return-into-lib(c) exploits” and basically introduced a new techniques known as return-to-plt. This technique was able to defeat the first ASLR implementation. Then the PaX team strengthen the ASLR implementation and introduced a new feature to defend against return-to-plt. As expected this technique didn’t last long without a comprehensive study on how to bypass it. It was August 2002 and Tyler Durden published an article on Phrack issue 59 titled “Bypassing PaX ASLR protection”.

Today, ASLR is adopted by many Linux distributions. Nowadays is built into the Linux Kernel and on Debian and Ubuntu based systems is controlled by the parameter  /proc/sys/kernel/randomize_va_space. This mitigation can be changed with the command “echo <value > /proc/sys/kernel/randomize_va_space ” where value can be:

  • 0 – Disable ASLR. This setting is applied if the kernel is booted with the norandmaps boot parameter.
  • 1 – Randomize the positions of the stack, virtual dynamic shared object (VDSO) page, and shared memory regions. The base address of the data segment is located immediately after the end of the executable code segment.
  • 2 – Randomize the positions of the stack, VDSO page, shared memory regions, and the data segment. This is the default setting.

Interesting is the fact that on 32-bit Linux machines an attacker with local access could disable ASLR just by running the command “ulimit -c”. A patch has just been released to fix this weakness.

Following the work of StackGuard, the IBM researcher Hiroaki Etoh developed ProPolice in 2000. ProPolice is known today as Stack Smashing Protection (SSP) and was created based on the StackGuard foundations. However, it brought new techniques like protecting not only the return stack frame address as StackGuard did but also protecting the frame pointer and a new way to generate the canary values. Nowadays this feature is standard in the GNU Compiler Collection (GCC) and can be turned on with the flag “-fstack-protector”.  Ben Hawkes in 2006 presented at Ruxcoon a technique to bypass the ProPolice/SSP stack canaries using brute force methods to find the canary value.

Time passed and in 2004, Jakub Jelinek from RedHat introduced a new technique known as RELRO. This mitigation technique was implemented in order to harden data sections of ELF binaries.  ELF internal data sections will be reordered. In case of a buffer overflow in the .data or .bss section the attacker will not be able to use the GOT-overwrite attack because the entire Global Offset Table is (re)mapped as read only which will avoid format strings and 4-byte write attacks. Today this feature is standard in GCC and comes in two flavours. Partial RELRO (-z relro) and Full RELRO (-z relro -z now). More recently, Chris Rohlf wrote an article about it here and Tobias Klein wrote about it on a blog post.

Also in 2004 a new mitigation technique was introduced by RedHat engineers. The technique is known as Position Independent Executable (PIE). PIE is ASLR but for ELF binaries. ASLR works at the Kernel level and makes sure shared libraries and memory segments are arranged in randomized addresses. However, binaries don’t have this property. This means the addresses of the compiled binary when loaded into memory are not randomized and become a weak spot for protection against buffer overflows. To mitigate this weakness, RedHat introduced the PIE flag in GCC (-pie). Binaries that have been compiled with this flag will be loaded at random addresses.

The combination of RELRO, ASLR, PIE and Non-executable stack raised significantly the bar in protecting against buffer overflows using return-to-libc technique and its variants. However, this didn’t last long. First Sebastian Krahmer from SUSE developed a new variant of return-to-libc attack for x64 systems. Sebastian wrote a paper called “x86-64 buffer overflows exploits and the borrowed code chunks exploitation technique”.

Then with an innovative paper published on ACM in 2007, Hovav Shacham wrote “The Geometry of Innocent Flesh on the Bone: Return-into-libc without Function Calls (on the x86)”. Hovav introduced the concept of using return oriented programming and what he called gadgets to extend the return-to-libc technique and bypass different mitigation’s enforced by the Linux operating system. This technique was based on the work from Solar and Nergal and does not need to inject code and takes advantage of existing instructions from the binary itself. Reuse existing instructions and chain them together using the RET instruction to achieve the end goal of manipulating the program control flow execute code of attackers choice. This is a difficult technique to perform but is powerful and is known as ROP. A summary was  presented by Hovav on Black Hat 2008.

Also, in 2008, Tilo Müller wrote “ASLR Smack & Laugh Reference” explaining the different attacks against ASLR in a comprehensive study that outlines the various techniques. In 2009 the paper “Surgically returning to randomized lib(c)” from Giampaolo Fresi Roglia also explains how to bypass non-executable stack and ASLR.

In 2010, Black Hat had 3 talks about Return-Oriented exploitation. More recently and to facilitate ROP exploitation, the French security researcher Jonathan Salwan wrote a tool written in Python called ROPgadget. This tool supports many CPU architectures and allows the attacker to find the different gadgets needed to build its ROP chain. Jonathan is also gives lectures and makes his material accessible. Here is the 2014 course lecture on Return Oriented Programming and ROP chain generation. ROP is the current attack method of choice for exploitation and research is ongoing on mitigation and further evolution.

Hopefully, this is gives you good reference material and a good overview about the evolution of the different attacks and mechanisms against  Stack based buffer overflows. There are other type of buffer overflows like format strings, integer overflows and heap based but those are more complex. Buffer Overflows is a good starting point before understanding those. Apart of all the material linked in this article, good resources for learning about this topic are the books Hacking: The Art of Exploitation by Jon Erickson, The Shellcoder’s Handbook: Discovering and Exploiting Security Holes by Chris Anley et.al., and A Bug Hunter’s Diary: A Guided Tour Through the Wilds of Software Security by Tobias Klein.

 

Tagged , , , , , ,

Security Hands-On-Training – Part 6 – Final

The previous blog post illustrated how someone with malicious intent could pull off a way to compromise a system. It starts by gaining access to the system using a SQL injection. After the initial access a foothold is established. Then the position is strengthen by uploading the tools of choice. Next the privileges are escalated and a shell with full systems privileges is gained.

However, this attack method might seem complex it would probably happen in case there is a motive or incentive for the attacker do it. An incentive to do such activity could be to steal trade secrets, intellectual property, credit cards or any other information that the attacker could monetize. Nonetheless, there are other motives that serve as an incentive for an attacker to compromise a system. Brian Krebs, a former Washington Post reporter, has putted together a great chart listing the various ways the bad guys can monetize hacked systems (Krebs, 2012).  One of the attack methods that tend to gain popularity is to use SQL injection for malware distribution. Basically, by introducing malicious code in the web server an attacker can turn the web server in a mechanism to deliver malicious code to browsers by taking advantaged of client-side vulnerabilities against unpatched browsers. This mechanism was used by the Asprox botnet (Borgaonkar, 2010) (Pelaez, 2008).  More recently this attack gained the connotation of watering hole or strategic web compromise when it targets a trustworthy web site (Kindlund, Caselden & Chen, 2014). Steven Adair and Ned Moran explain it perfectly in his article about trusted websites delivering dangerous results (Adair & Moran, 2012).

How does an attacker performs this? What are the mechanics behind such method? As the reader noticed in the previous attack scenario there were some key aspects that would be important for the attacker to be successful. One item is the xp_cmdshell stored procedure being enable or the ability to have an out-of-band channel to accelerate the speed of the time based SQL injection technique. But, in the watering hole attack scenario there is no need of any of those factors. The attacker will only need a SQL injection point and from there it can inject malicious script that will be appended trough out the database. As consequence, when a user browses to the web page, the data is retrieved from the database and rendered in the browser. Then the malicious code is executed putting him at mercy of all kind of client-side exploits.

Figure below illustrate these steps using a SQL statement that is famous due to the Asprox Trojan (Analysis, 2008) (Shin, Myers & Gupta, 2009). It  uses a special table in the SQL server sysobjects and syscolumns in an attempt to get access to the “user” defined tables and fields in the website’s database. Through a loop it goes through every table columns and appends a string containing the malicious <script> tag.

This SQL statement is encoded in a hex format and inserted into another SQL statement in order to evade defenses.  The reader can practice this technique and use SQLmap to invoke a SQL shell that allows to execute SQL statements.  Then this prepared statement is executed which will result in infecting the database data. For reference a picture of what DBA will see if he looks into is affected database is also shown.

security-hot-fig29

From this moment onwards the web server is infected. When a user goes in and browses trough the infected web pages it will download and execute the evil Java Script within the <> tags (Stuck, 2009) (Mendrez, 2009). This evil script can do, among other things, scan the visitor machine for client side vulnerabilities and deliver the appropriate exploit payload. Similar to using guided missiles this attack can be very effective and is worth to mention James Lee presentation “Using Guided Missiles in Drive­bys  at Defcon 17“.

As demonstrated using this environment the reader could get a practical understanding of how a typical watering hole attack is executed. The next step might be to explore the client side vulnerabilities and exploits by taking advantage of the evil script that is inserted into the database.  The reader is encouraged to further learn, practice and explore this vector of attack with tools such as the Browser Exploitation Framework (BeEF) developed by Wade Alcorn and others, or  the Social Engineering Toolkit (SET) from David Kennedy.

Continuing the Journey

Even though the tools used are extremely functional and almost no knowledge is needed to run an exploit against a vulnerable server using SQLmap or Metasploit this is the first step in building hands-on information security skills. Some techniques used are low hanging fruit. Nonetheless, the reader should start with them in order to advance to more complex methods and techniques using incremental approach.  A proposed next step would be to further expand this environment to model business networks with end point and boundary defenses such as a Proxy, an IDS/IPS, a HIDS, etc. Also introduce Linux based systems such as an e-commerce and test other techniques and exploits (Rocha, 2012). As well, the reader could create scenario based challenges and simulations like Ed Skoudis promotes on his presentation “Using InfoSec Challenges to build your skills and career” that can emphasize the development of critical thinking (Skoudis, 2012).

Further practice reconnaissance, scanning, exploitation, keeping access and covering tracks will be doable. In addition to offensive skills the reader might want to practice defensive skills. When the attacker launches a specific technique  how does it look like? Which opportunities does it bring from a defender to identify and detect it from the network or database level? How does it look at the operating system level. How would the reader be able to better prepare, identify, contain, eradicate and recover from each one of these and other attack scenarios. Could the correlation between the logs from the DNS server and Database server be used to detect such incident? Which IDS signatures would be needed to detect this kind of traffic? This and other suggestions have been also encouraged throughout the previous chapters.

It’s this never ending cat and mice game which makes our industry a very interesting place to be at. Like when playing a game, It involves defenders trying to build a secure system, then how to innovate, progress and take it to the next level by circumvent those measures using different tools and techniques. Then the defender improves the system and so on. This healthy competition between the attacker and the defender will make us smarter and better at security. As Jon Erickson mention on his book “The net result of this interaction is positive, as it produces smarter people, improved security, more stable software, inventive problem-solving techniques, and even a new economy”.

Conclusion

Although there are plenty of books and open source information that describe the methods and techniques demonstrated, the environment was built from scratch.  The tools and tactics used are not new. However, they are relevant and used in today’s attacks. Likewise, the reader can learn, practice and look behind the scenes to better know them and the impact they have.

The main goal was to demonstrate that hand’s on training is a very valuable and cost efficient training delivery method that allows a better practical understanding on security. This method has advantages to build up your skills – not only from an incident handling and hacking techniques perspective but also from a forensics perspective.  One can practice and improve their ability to determine past actions which have taken place and understand all kinds of artifacts which occur within the outlined scenarios. For instance, one could simulate an actual forensic investigation!  On the other hand, from an Intrusion Analyst’s perspective the reader can capture the full contents of the network packets during the exercises and work on mastering his TCP/IP and intrusion detection techniques. In addition to that, the data set can be also feed to intrusion detection devices in order to measure how effective will they be in detecting the attacks.

Practice these kind of skills, share your experiences, get feedback, repeat the practice, grow to be proficient,  improve your performance and become fluent.

 

 

References

Krebs, B. (2012, 10 15). The scrap value of a hacked pc, revisited. Retrieved from http://krebsonsecurity.com/2012/10/the-scrap-value-of-a-hacked-pc-revisited/)
Borgaonkar, R. (2010). An analysis of the asprox botnet. Manuscript submitted for publication, .
Pelaez, M. (2008, 8 15). Obfuscated sql injection attacks. Retrieved from https://isc.sans.edu/diary/Obfuscated SQL Injection attacks/9397
Kindlund, D., Caselden, D., & Chen, X. (2014, 02). [Web log message]. Retrieved from http://www.fireeye.com/blog/uncategorized/2014/02/operation-snowman-deputydog-actor-compromises-us-veterans-of-foreign-wars-website.html
Adair, S., & Moran, N. (2012, 05 12). [Web log message]. Retrieved from http://blog.shadowserver.org/2012/05/15/cyber-espionage-strategic-web-compromises-trusted-websites-serving-dangerous-results
Analysis, X. (2008). Asprox trojan and banner82.com . Retrieved from http://xanalysis.blogspot.ch/2008/05/asprox-trojan-and-banner82com.htm
Shin, Y., Myers, S., & Gupta, M. (2009). A case study on asprox infection dynamics. Manuscript submitted for publication, Computer Science Department, Indiana University, .
Stuck, F. (2009). An overview of a sql injection attack. Retrieved from http://geek37.net/Portfolio_SQL_Injection_Presentation.html
Mendrez, R. (2009). Another round of asprox sql injection attacks. Retrieved from http://labs.m86security.com/2010/06/another-round-of-asprox-sql-injection-attacks/
Rocha, L. (2012, Nov 23). Hands-on lab – ecommerce – part 1. Retrieved from https://countuponsecurity.com/2012/11/23/hands-on-lab-ecommerce-part-1/
Skoudis, E. (2012, March). [Web log message]. Retrieved from https://blogs.sans.org/pen-testing/files/2012/03/Put-Your-Game-Face-On-1.11.pdf

Tagged , , , , , , , , , ,

Security Hands-On-Training – Part 5

[Now that we have the environment ready we can start looking at the different attack methods. The goal is to practice the tools, look behind the scenes and understand the techniques that might be used to gain access, establish a foothold, escalate privileges, steal credentials and exfiltrate data. With this one can learn, practice and gain a better practical understanding on security. ~Luis]

Ed Skoudis describes the anatomy of an attack using a 5 step model. The steps are reconnaissance, scanning, exploit, keeping access, and covering tracks (Skoudis & Liston, 2005). In our environment, the reconnaissance and scanning steps are skipped. The focus will go be on the exploit phase. A sophisticated intruder will spend a great amount of time and resources performing reconnaissance and scanning.

We will use SQL Injection as an example and utilize SQLmap in this exercise. SQLmap has been developed by Bernardo Damele A.G. and Miroslav Stampar and it is an actively maintained and powerful command line tool. It is available as part of the BackTrack and Kali distribution (SQLmap).

Start by getting the latest version of SQLmap from the repository by issuing the command shown below.

security-hot-fig16

To configure SQLmap, we will tweak the default settings. In order to get those settings the reader should access the test site through a proxy like Paros or use the Firefox tamper data plug-in. Save all the POST parameters in a file which will be used as payload. The nest figure shows the steps taken to retrieve the POST parameters and use them.

security-hot-fig17

Then execute SQLmap.  It will determine that the parameter ctl00$ContentPlaceHolder1$descriptionTextBox is vulnerable using a time-based blind SQL injection technique. Using this technique the tool is able to extract the SQL query results in a bit-by-bit manner (Litchfield, 2005). Asking questions to the database and observing how it reacts to those questions will allow the attacker to infer the value of the data (Stampar, 2009) (Litchfield, 2005).

Now that the reader has a method that works and that allows him to have access to the system, the reader can move to more advanced techniques. Figure below exemplifies in detail how SQLmap achieves an operating system shell using time-based blind injection techniques. It starts by determine if the current user is part of the sysadmin role. Then it determines if the xp_cmdshell extended procedure is available. This stored procedure is one of the most powerful stored procedures and it is used to launch operating system commands in the context of the SQL server service (Litchfield, Anley, Heasman & Grindlay, 2005). In this case it was not available so SQLmap has the ability to re-enable it using the sp_configure stored procedure. The reader needs to have sysadmin rights to the DB to use sp_configure. With xp_cmdshell, the reader can start executing operating system commands using SQL statements. Because the results of the xp_cmdshell are not sent to the client, further queries using temporary tables are used to retrieve the results.

security-hot-fig18

SQLmap is able to retrieve data over out of band channels such as DNS. This technique allows the retrieval of the SQL results using a DNS recursive resolution process which is much faster than the time-based or boolean-based inference methods (Stampar, 2009). To accomplish this, the attacker needs to control a DNS domain name. Of course the database server also needs to have a dns server configured and be able to perform queries.

The DNS requests made by the database will be triggered by SQL queries. Due to the way DNS works, if the database does not know the answer, it will forward the request to the upstream DNS server. In our environment ,the system does not have access trough the firewall for any outbound communications. Nevertheless, it can forward the DNS requests to the DNS server which in turn forwards them to the authoritative server which is under the attacker’s control. Sensepost presented at BlackHat USA 2007 a SQL injection tool called Squezza that was able to extract data trough DNS and others channels (Research, 2007). This technique was added to SQLmap in 2012 (Stampar, 2009). To carry out this technique, SQLmap will be executed with a command line option that specifies the domain name controlled by the attacker. Figure below shows the command executed, the SQL queries performed, and the output of the commands. It also shows how the DNS queries are constructed.

security-hot-fig19

After executing this technique, a low privilege shell is gained. The next step will be to strengthen the position within the target by uploading additional tools to the system to escalade privileges. In addition, since it is known the system can communicate via DNS, a different set of tools will be used to take advantage of this and further compromise the system. This combined arms approach will result in use getting a “system” privilege shell back via DNS.

To escalate privileges a tool called churrasco developed by Cesar Cerrudo is used. This tool takes advantage of an exploit that uses a technique that he named as token

kidnapping which elevates privileges to a System account by using techniques that impersonate tokens to manipulate processes and thread access lists (Cerrudo, 2008). The source code of the tool that affects Windows 2008 was downloaded from Cesar Cerrudo’s website and compiled using Visual Studio C++ 2008 Express edition (www.argeniss.com/research/Churrasco2.zip). It is important to note that this vulnerability has been patched by Microsoft in Windows 2012 (MS09-12). The exploit when executed successfully will span a shell to an IP and port chosen by the user.  In spite of this, because the firewall does not allow the target system to communicate with the outside world, the shell will communicate back to the attacker through DNS. We will use dns2tcp. This tool allows relaying TCP connections trough DNS. This way the spanned shell from the exploit will be redirected and forwarded using DNS (Dembour).

These tools will be uploaded to the system, written to the file system in a directory where the low privilege account would have write access and then executed. To accomplish this the reader starts by uploading the dns2tcp client tool ( dns2tcpc.exe) using  SQLninja, a powerful SQL injection tool created by Icesurfer (SQLninja). The same way SQLmap needed configuration settings, SQLninja will need the target details, the injection point and a well formed HTTP request. This is done via SQLninja.conf and the HTTP POST request used is shown in the next figure.

security-hot-fig20

The methods used by either SQLmap or SQLninja to upload files and write them to the file system using SQL injection are based on the xp_cmdshell procedure. This procedure can facilitate the creation of files by using the “>>” redirect operator (Clarke, 2012). Behind the scenes SQLninja can use two techniques to upload files to target systems. One technique is to base64 encode the binary and then upload it. The other technique uses an old trick to convert the binary into a DEBUG script.  The default technique is to use the base64 method and it can be defined in the sqlninha.conf by stating “upload_method = vbscript”.  Figure 22 illustrates this technique.

security-hot-fig21

This technique works well. The alternative technique creates a DEBUG script which can be passed to the debug.exe script to be converted to a binary. The following picture shows the steps taken by SQLninja to accomplish this.

security-hot-fig22

Compared to using a Base64 encoded binary, this technique has the disadvantage that debug.exe can only build executables smaller than 64 Kb. However, you can split bigger files into 64 KB portions and after uploading them you can concatenate them together using copy /b portion _1  + portion_2 original-file.exe (Clarke,2012).  This technique is slower but as the advantage that debug.exe is available in any windows operating system and therefore the attacker won’t need any additional scripts or tools to create a binary on the target system. More details about debug.exe is available on Kipivirne.com.

In case the reader would like to try the DEBUG technique he can convert windows binaries to a debug script format in Backtrack using a python script called dbgtool.py. Is available  in the SQLmap directory under /extra/dbgtool/. Then the file containing the debug script can be moved to a windows machine and converted back to a binary using the “debug < debugfile” command.

The reader can follow the same process to upload any additional tools. The target system does not use any antivirus tools, but this technique can be performed even with antivirus. The traditional way that antivirus programs identify the presence of a virus is by using signatures (Labbe, Rowe & Fulp, 2006). This can be subverted by using an exploit that the antivirus tool does not have a signature for. One simple way to do this is to use a hex editor to remove the machine code that triggers the signature without having an impact on the execution of the exploit. Another way might be by using encoders or packers or even target the AV software itself (Ormandy, 2012)(Koret, 2014). This is left as an exercise for the reader to further research.

The next tool to be uploaded is churrasco.exe. We need to configure SQLninja to be aware of this tool in order to allow it to be uploaded to the target. This is done by adding lines of code to sqlninja.py to identify the file, and adding the file to the sqlninja/apps folder.

Now that the dns2tcpc.exe and churrasco.exe tools are uploaded the next step is to execute them. Because they need to be executed sequentially, the task scheduler in windows will be used. This can be invoked from the command line using the schtasks.exe command. The schedule of the tools execution will be done using the interactive command line that can be invoked by the SQLmap os-shell feature.

First SQLmap is launched. Then it checks if the files are saved in the %TEMP% folder. Finally, two tasks are scheduled to run daily at pre defined times with current privileges. The first task executed is “dns2tcpc”. The command line instructs dns2tcpc.exe to encapsulate the data using DNS requests to the acme.com domain with using a pre-shared key. In addition, it instructs the server side of the tool to use the ssh resource and to listen for incoming connections on port 137 TCP (Dembour). The second task executed is “churrasco.exe”. The command line instructs churrasco to execute a reverse shell to localhost on port 137 which is where dns2tcpc.exe is listening. These steps are illustrated below.

security-hot-fig23

After successful scheduling the tasks, the reader needs to exit SQLmap to release UDP port 53 (remember SQLmap is using this port while launching the commands trough encapsulated DNS queries). Then it executes the dns2tcp server daemon. This tool is available on the backtrack distribution under /pentest/backdoors/dns2tcp. Before executing the daemon the reader  needs to create a configuration file in the user’s home folder, configuring the IP address and the port to listen on, the domain name send questions to, the pre-shared key, and where to redirect the connections received.  The directory specified in the chroot settings of the configuration file also needs to be created beforehand.

security-hot-fig24

After defining the configuration file, dns2tcpd is instructed to listen on IP address 192.168.1.7 (-i), execute on the foreground (-F) and show debug level information so the queries and answers can be seen (-d 3). Then the reader will need to wait for the scheduled tasks to kick in.

security-hot-fig25

While waiting for the scheduled tasks to start, another shell is needed. This shell will listen for an incoming connection on localhost port 22 which is going to be forwarded by our dns2tcp daemon. To do this the Metasploit mutil-handler is used. This will handle the reverse connection but the reader could simple use netcat (nc -l -p 22).

At this stage the attacker has two shells open. One to answer the DNS queries addressed to the domain acme.com. These will contain encapsulated data which are  shell code that is going to be forwarded to port 22. On the second shell there is Metasploit multi-handler waiting for that shell code. When the scheduled tasks triggers a TCP reverse shell with system privileges encapsulated trough DNS data will be opened. The following figure demonstrates how these techniques work together.

security-hot-fig26

The next picture illustrates a summary of the techniques used.

security-hot-fig27

Now, that the reader has escalated privileges and maintains access he can steal valid user credentials.  To steal credentials there are a variety of tools and ways. In this case a tool named gsecdump v2.0b5  created by Johannes Gumbel from TrueSec that allows extracting the hashes from SAM or AD database will be used (TrueSec). This tool is uploaded to the target system like it was shows previously. The execution is shown below. With the hashes extracted the reader can then crack them using the John the Ripper or Hashcat. Or, it can use the hashes to further move into the network by using passing the hash or pass the ticket techniques (Rocha, 2012).

security-hot-fig28

From this moment onwards the reader can further practice tools and techniques to increase his presence in the target, move and compromise other targets in the network, steal and exfiltrate data and finally cover his tracks.

 

References:

Skoudis, E., & Liston, T. (2005). Counter hack reloaded: A step-by-step guide to computer attacks and effective defenses, second edition. Prentice Hall.
Ormandy, T. (2012). Sophail: A critical analysis of sophos antivirus. Retrieved from http://lock.cmpxchg8b.com/Sophail.pdf
Ormandy, T. (2012). Sophail: Applied attacks against sophos antivirus. Retrieved from http://lock.cmpxchg8b.com/sophailv2.pdf
Koret, J. (2014, January 1). . . Retrieved , from http://www.slideshare.net/JoxeanKoret/breaking-av-software-33153490
TrueSec. (n.d.). gsecdump v2.0b5. Retrieved from https://www.truesec.se/sakerhet/verktyg/saakerhet/gsecdump_v2.0b5
SQLmap.(n.d.) Retrieved from http://sqlmap.org/
SQLninja. (n.d.). sqlninja. Retrieved June 7, 2014, from http://sqlninja.sourceforge.net/
Stampar, M. (2009). Data retrieval over dns in sql injection attacks. (Master’s thesis)Retrieved from http://arxiv.org/ftp/arxiv/papers/1303/1303.3047.pdf
Rocha, L. (2014, Jul 2). The path to the Golden Ticket. Retrieved from https://countuponsecurity.com/2014/07/02/the-path-to-the-golden-ticket/
Litchfield, D. (2005, March). Sql injection and data mining trough inference. Backhat europe 2005.
Research, S. (2007). Squeeza. Retrieved from http://research.sensepost.com/tools/servers/squeeza
Cerrudo, C. (2008, 5 17). Token kidnapping. Retrieved from http://www.argeniss.com/research/TokenKidnapping.pdf
Dembour, O. (n.d.). dns2tcpc – a tunneling tool that encapsulate tcp traffic over dns. Retrieved from http://manpages.ubuntu.com/manpages/raring/man1/dns2tcpc.1.html
Clarke, J. (2012). Sql injection attacks and defense, 2nd edition. Syngress.\
Labbe, Keith, Rowe, Neil & Fulp, J.D. (2006). A Methodology for Evaluation of Host Based Intrusion Prevention Systems and its Applications, 2006 IEEE Information Assurance Workshop

Tagged , , , , , , , , , , ,

Security Hands-On-Training – Part 4

[Following part 3 where the  ASP.NET web site code was modified, part 4 will show different methods, techniques, and ways of manipulating the user input in order to control the logic of the application making the web application exploitable. ~Luis]

During the previous chapter the defenses that were in place in the test application were removed. To achieve this a  trial and error approach was used. While looking for SQL injection vulnerabilities, different methods, techniques, and ways of manipulating the user input were tried in order to see how the system reacted. This method allows us to learn and practice which defenses would need to be removed to allow a successful exploit.

The HelpDesk.aspx page is shown in the next figure. It simulates a helpdesk ticketing system where the user is allowed to input data into two fields. The “Station Number” and the “Problem Description”.

security-hot-fig9

When the user clicks on the “Submit Request” button, the web form takes the value and passes it to a SQL statement. This will happen without validation controls because they were removed in the previous post. Behind the scenes this page contains an INSERT SQL statement that will receive the user input and insert it into the database. The code block that allows this to happen is shown below.

security-hot-fig10

The database called “Dorknozzle” contains a table called “HelpDesk”. This is shown in the below figure. In the database there are several columns that are used to store the user input. During the trial and error method to discover a SQL injection point  it was found that input that is stored in the database as an integer could not be manipulated.  This applies to the “Station Number” field. However, the “Description” field uses the nvarchar type and allows up to 50 characters to be inserted.

security-hot-fig11

With this in mind and with the defenses down the reader can start adding characters in the user input fields that would change the initial query logic and see how the system reacts. The first character to try is the single quote. When clicking the submit button the web application returns a SQL exception message. This happens because the error messages were enabled.

security-hot-fig12

This was exactly the objective. This SQL error message discloses that the statement submitted had an unmatched number of single quote characters. To further exploit it the reader would need a way to construct a statement in the input field that allowed to terminate the string and append the malicious SQL statement (OWASP,4). At this stage the debug functionality of Visual Studio Express was used. By introducing a break point in the code where the SQL statement is, the application execution could be controlled. Then the Web application was started in debug mode. In the HelpDesk page the character “A” and a single quote was inserted in the “Problem Description” field. When submitting the request the break point kicked in and the step into functionality was used to dig into what was happening. This allows us to verify exactly how the SQL statement was being constructed and executed by the database. The next figure shows these steps.

security-hot-fig13

The SQL statement that was being sent to the database was not well formed due to the crafted input which caused an odd number of single quote characters resulting in a SQL error. The below figure shows what the SQL statement looks like.

security-hot-fig14

Now it is just a manner of time to find the correct input that will create a well formed SQL statement and introduce the malicious SQL code. During this iterative process the reader can find that he could close the SQL statement by injecting the right number of values that the database is expecting. Then another statement could be inserted and this would be the injection point and the “–“ sequence (two dashes) can be used to ignore the rest of the statement. This SQL injection point is inside an INSERT statement. Because of this you couldn’t see the output of the injected query or any difference in the in the responses of the web application which increases the difficulty of the technique. Using a technique called Blind SQL injection, which was first introduced by Chris Anley in 2002, the reader  might use inference techniques to get the results (Clarke, 2012). For example, with this technique, SQL statements that analyze the response time can be used. One method is using the sleep function like WAITFOR DELAY ‘time’. Using this technique the reader could make the database wait and reveal if a statement was true or false. In the next figure is shown how the SQL statement would look like after having the evil payload inserted. This will result in the database to wait 5 seconds before producing the results.

security-hot-fig15

In addition to the previous example the following SQL statements could be used in the SQL injection point to understand how the database would react:

IF (1=1) WAIT FOR DELAY ‘0:0:5’ —
IF (1>2) WAIT FOR DELAY ‘0:0:5’ —

Then more advanced queries could be used to determine if the current user is part of the sysadmin role:

IF((SELECT (CASE WHEN (IS_SRVROLEMEMBER(‘sysadmin’)=1) THEN ‘1’ ELSE ‘0’ END))=’1′) WAITFOR DELAY ‘0:0:5’ –

This seems a rather tedious and slow process but this will be automated using well known SQL injection tools in the upcoming articles. These tools dramatically increase the efficiency of an attacker but also extend the attack population. One disadvantage of these powerful tools is that any inexperienced person can mount complex SQL injection attacks regardless the technique or the database technology (Clarke, 2012).

During this exercise the reader is able to learn about SQL, its inner working queries and how SQL statements are constructed. It should be clear now why is important to disable any error messages and  why it is important to sanitize all input. When the reader has a good understanding of the tools and techniques and can control the logic of the application the reader could also use SQL injection with serious consequences. Tools like SQLmap and SQLninja can be used to automate these techniques.

Even though the focus was on SQL injection the environment is ready for additional tests by reducing our defenses further. In the context of this web application the reader could introduce other vulnerabilities such as Cross-Site scripting (XSS), Cross-Site Request Forgery (CSRF) or introduce a broken authentication mechanism. Learning how to do this and understanding the mechanisms behind the scenes is a rewarding exercising. Likewise, learning the attack vectors, use the tools, taking the time to experiment with them and understand how they work will make one better equipped and skilled.

 

References:
OWASP. (4, September 13). Testing for sql injection (owasp-dv-005). Retrieved from https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OWASP-DV-005)
Clarke, J. (2012). Sql injection attacks and defense, 2nd edition. Syngress.

Tagged , , , ,

Security Hands-On-Training – Part 3

[Following part 1 and part 2 where we built an infrastructure with different systems, below article will focus on the Web Stack and will show how the ASP.NET code has been modified in order to make the application less secure. This will allow us to understand the security mechanism enforced by the application in order to make it defenseless and practice our security tools and techniques! ~Luis]

Instead of modifying the secure test application, the reader could use an existing vulnerable web application. Likewise, the reader could use test sites that allow him to practice hacker techniques in a wide variety of security realms. Just chose one from Aman Hardikar’s awesome mind map with various penetration testing practice labs and vulnerable applications (Hardikar, 2013). But on the other hand, building an infrastructure with simple IT services such as directory services, messaging services and a web stack  will allow the reader to enhance the depth and breadth of its skills not only from a security perspective but also from a systems and networking viewpoint.

Also, It is valuable to be exposed to defense and offense. Through the process of creating this environment and then growing it at will, the reader can practice both sides. In this environment a simple and secure web application is created and then its defenses are reduced. For instance, while following the mentioned book to create an ASP.NET website the code uses strong protections against SQL Injection using parameterized queries, stored procedures and data validation controls (Posey, Barnett & Darie, 2011). To make the application less secure, the reader first has to understand the security techniques employed by this application. The same applies to other technologies. For example techniques that protect against malicious user input. Once the code is vulnerable, the reader can explore attack techniques.

After building the mentioned web application – the code is available for free on GitHub -, 4 steps are executed to make it vulnerable: First, a user account with system administration privileges is created. Second,  the SQL parameterized statements are replaced by dynamic SQL statements. Third, the code is changed to make the application disclose error information and finally, the data validation code is removed to avoid input sanitization based on type, length, format or range.

For step one, go into the SQL Management Studio on your database server and create a user with system administration privilege (sysadmin) as illustrated in the left side of the following figure.
security-hot-fig5

This user will be used to define a database connection using SQL authentication. Then start changing the .NET application code using Visual Web Developer 2010 Express. For reference the right side of previous figure shows how these code files look. Next, web.config is modified. The authentication mechanism used by the application to connect to the database will change from integrated authentication to SQL authentication as shown on the left side of below figure (Posey, Barnett & Darie, 2011).  After making the change make sure the application can be compiled and is working as expected. Next change HelpDesk.aspx.cs. Remove the block of code that contains the parameterized SQL statements and replace it with a dynamic SQL as shown in right side of the following figure.

security-hot-fig6

Following that, step three is to customize the Try-Catch-Finally code block in HelpDesk.aspx.cs as shown on the below figure. This allows the web application to throw error messages and disclose them locally. Finally change HelpDesk.aspx and remove input data validation by commenting it out. This will facilitate the attack methods later on. The left side of the below figure shows the code block that should be removed or commented.

security-hot-fig7

In addition,  disable the EnableEventValidation and ValidateRequests directives by setting them to false in the header of the HelpDesk.aspx (see below figure).

security-hot-fig8

By following these steps the reader made the HelpDesk.aspx page vulnerable to SQL injection. This is going to be demonstrated in the next articles. It is not an intent to make the reader a .NET developer. Still, it is up to the reader if  he wants to further read and explore more about what are those measures that were removed or just follow the steps in order to practice the tools and tactics in the upcoming articles.

 

References:
Hardikar, A. (2013, 06). Penetration testing practice lab – vulnerable apps / systems. Retrieved from http://www.amanhardikar.com/mindmaps/Practice.html
Posey, T., Barnett, W., & Darie, C. (2011). Build your own asp.net 4 web site using c# & VB, 4th edition. SitePoint

 

Tagged , , ,