Penetration testing

Advanced sqlmap

SecRat
July 10, 2014 by
SecRat

sqlmap is an attack tool which can be effectively used to perform SQL injection attacks and post exploitation acts. It is a versatile tool when it comes to SQL injections. Most security professionals use sqlmap for SQL injection related pen tests.

sqlmap is a modular framework written in Python. It can detect most of the SQL injection flaws across the different platforms. The following databases are supported: ySQL, Oracle, PostgreSQL, Microsoft SQL Server, Microsoft Access, IBM DB2, SQLite, Firebird, Sybase and SAP MaxDB.

FREE role-guided training plans

FREE role-guided training plans

Get 12 cybersecurity training plans — one for each of the most common roles requested by employers.

After exploitation is successful, it can enumerate databases and tables and also can dump database and tables.

This tool can be downloaded from: http://sqlmap.org/

In this tutorial we will explore a very powerful feature of sqlmap: .ie tamper scripts. Usually when you are trying to exploit an SQL injection flaw, the most basic and conventional attack vector is http. Now what if the medium is different or if it is using some kind of different encoding? That's where tamper scripts come in to help. We can use tamper scripts to decode and encode data before it is passed to sqlmap.

sqlmap introduction

After downloading sql map from the website, sqlmap can be started using the sqlmap command in the install directory.

Following is the basic usage of sqlmap.

Target:

At least one of these options has to be provided to set the target(s).

-d DIRECT Direct connection to the database

-u URL, --url=URL Target URL (e.g. "www.target.com/vuln.php?id=1")

-l LOGFILE Parse targets from Burp or WebScarab proxy logs

-m BULKFILE Scan multiple targets enlisted in a given textual file

-r REQUESTFILE Load HTTP request from a file

-g GOOGLEDORK Process Google dork results as target URLs

-c CONFIGFILE Load options from a configuration INI file

Request:

These options can be used to specify how to connect to the target URL.

--data=DATA Data string to be sent through POST

--param-del=PDEL Character used for splitting parameter values

--cookie=COOKIE HTTP Cookie header

--cookie-del=CDEL Character used for splitting cookie values

--load-cookies=L.. File containing cookies in Netscape/wget format

--drop-set-cookie Ignore Set-Cookie header from response

--user-agent=AGENT HTTP User-Agent header

--random-agent Use randomly selected HTTP User-Agent header

--host=HOST HTTP Host header

--referer=REFERER HTTP Referer header

--headers=HEADERS Extra headers (e.g. "Accept-Language: frnETag: 123")

It also supports a Python based API . You can include this file in your Python script to automate and run sqlmap.

Sqlmapapi.py can be used to start A RPC server for sqlmap.

if args.server is True:

server(args.host, args.port)

elif args.client is True:

client(args.host, args.port)

Now let's try to harness the power of sqlmap and perform a local attack using SQL injection.

After successfully exploiting the server, we can perform the following post exploitation attacks:

Defeating encoding using tamper scripts

One of the most beautiful things about sqlmap is that it can be extended to work on custom encoding. Usually many tools or conventional SQL injectors fail on custom encoding schemes. We can write tamper scripts for sqlmap to bypass encoding.

Let's consider this situation where the data in the web application is encoded before passed to a function.

[php]

<?php

$publicKey = openssl_get_publickey(file_get_contents("$dir/pubkey_rsa.pem"));

// encrypt the data
openssl_seal($data, $sealed, $ekeys, array($publicKey));

openssl_free_key($publicKey);

$sealed = base64_encode($sealed);

$privateKey = openssl_get_privatekey(file_get_contents("$dir/privkey_rsa.pem"));

openssl_open(base64_decode($sealed), $opened, base64_decode($Xevk), $privateKey)

or die(openssl_error_string());

openssl_free_key($privateKey);

passfunction($sealed)

?>
[/php]

We can write a tamper script to encrypt the data in RSA format. The following script shows how to tamper the data in RSA format.

[sql]

import base64

from Crypto.PublicKey import RSA

from Crypto import Random

from lib.core.enums import PRIORITY
from lib.core.settings import UNICODE_ENCODING

class MultipartPostHandler(urllib2.BaseHandler):
handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first

def http_request(self, request):
data = request.get_data()

if data is not None and type(data) != str:

v_files = []

v_vars = []

try:

for(key, value) in data.items():

if isinstance(value, file) or hasattr(value, 'file') or isinstance(value, StringIO.StringIO):

v_files.append((key, value))

else:

v_vars.append((key, value))

except TypeError:

systype, value, traceback = sys.exc_info()

raise SqlmapDataException, "not a valid non-string sequence or mapping object", traceback

if len(v_files) == 0:

data = urllib.urlencode(v_vars, doseq)

else:

boundary, data = self.multipart_encode(v_vars, v_files)

contenttype = 'multipart/form-data; boundary=%s' % boundary

#if (request.has_header('Content-Type') and request.get_header('Content-Type').find('multipart/form-data') != 0):

# print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data')

request.add_unredirected_header('Content-Type', contenttype)

request.add_data(data)
return request

def multipart_encode(vars, files, boundary = None, buf = None):

if boundary is None:

boundary = mimetools.choose_boundary()

if buf is None:
buf = ''

for (key, value) in vars:

buf += '--%srn' % boundary

buf += 'Content-Disposition: form-data; name="%s"' % key

buf += 'rnrn' + value + 'rn'

for (key, fd) in files:

file_size = os.fstat(fd.fileno())[stat.ST_SIZE] if isinstance(fd, file) else fd.len

filename = fd.name.split('/')[-1] if '/' in fd.name else fd.name.split('')[-1]

contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'

buf += '--%srn' % boundary

buf += 'Content-Disposition: form-data; name="%s"; filename="%s"rn' % (key, filename)

buf += 'Content-Type: %srn' % contenttype

# buf += 'Content-Length: %srn' % file_size

fd.seek(0)

buf = str(buf)
buf += 'rn%srn' % fd.read()

buf += '--%s--rnrn' % boundary

return boundary, buf
__priority__ = PRIORITY.LOWEST

def dependencies():
pass

def tamper(payload, **kwargs):

"""

Encrypts payload in RSA format

"""

random_generator = Random.new().read

public_key = key.publickey()

enc_data = public_key.encrypt(payload, 32)

What should you learn next?

What should you learn next?

From SOC Analyst to Secure Coder to Security Manager — our team of experts has 12 free training plans to help you hit your goals. Get your free copy now.

return enc_data
[/sql]

SecRat
SecRat

SecRat works at a start-up. He's interested in Windows Driver Programming.