Wednesday 1 April 2015

sqlmap Advanced Tutorial

sqlmap Advanced Tutorial

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.
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: 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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)
?>
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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 += '--%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
            fd.seek(0)
            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():
    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)
    return enc_data

2 comments:

  1. Do you need to increase your credit score?
    Do you intend to upgrade your school grade?
    Do you want to hack your cheating spouse Email, whatsapp, Facebook, instagram or any social network?
    Do you need any information concerning any database.
    Do you need to retrieve deleted files?
    Do you need to clear your criminal records or DMV?
    Do you want to remove any site or link from any blog?
    you should contact this hacker, he is reliable and good at the hack jobs..
    contact : cybergoldenhacker at gmail dot com

    ReplyDelete
  2. I Want to use this medium to appreciate an online ghost hacker, after being ripped off my money he helped me find my cheating lover and helped me hacked his WHATSAPP, GMAIL, kik and all his social media platforms and i got to know that he has being cheating on me and in less than 24 hours he helped me out with everything, hacking setting is trust worthy, contact him via: hackingsetting50@gmail.com

    ReplyDelete