Read the Sqlmap source code and write the Burpsuite plugin--sqlmapapi

Source: Internet
Author: User
Tags check sql injection sql injection

Burpsuite plug-in writing---SQL injection0x00 Overview

In the security testing process, most people will use Burpsuite's scanner module to test, you can find some obvious vulnerabilities: such as XSS, SQL injection, c***f, XXe, arbitrary file existence Disclosure in Act, clear text transmission, and so on.
When it comes to SQL injection, testers have an idea of whether there is an automated tool that can try to get all the links from one site to the next, as much as possible to find all the SQL injection. With this idea people will think about the solution, there is a solution is to write the Burpsuite plugin.

0x01 why SQLMAPAPI can only detect if a GET request exists for injection?

Write Burpsuite plug-in check SQL injection, there are already a lot of code on the Web.

In the same code, all the data on the Internet can only scan the link of Get request when the SQLMAPAPI is called, for example: http://www.xxx.com/index.php?id=1 cannot scan the parameters of post submission. At first I was always confused whether the Sqlmap did not provide the method or the predecessors did not write, so I looked at the source code of SQLMAP.
Basic procedure for calling Sqlmapapi:

Let's see why Sqlmapapi can't perform a post scan:
1. First look at the sqlmapapi.py file:

    # Start the client or the server    if args.server is True:        server(args.host, args.port, adapter=args.adapter, username=args.username, password=args.password)    elif args.client is True:        client(args.host, args.port, username=args.username, password=args.password)    else:        apiparser.print_help()

SQLMAPAPI when the service is turned on, our request in the plugin is a client, so we need to focus on client (Args.host, Args.port, Username=args.username, password= Args.password)

2, the Cilent function is located in the file:

3, because there is a lot of code in the api.py, line-by-row lookup is laborious, we directly search DEF client

4, Analysis cilent function

def client (host=restapi_default_address, Port=restapi_default_port, Username=none, Password=none): "" "REST-JSON API Client "" "Datastore.username = Username Datastore.password = Password Dbgmsg =" Example Client access from C Ommand line: "Dbgmsg + =" \n\t$ taskid=$ (Curl http://%s:%d/task/new 2>1 | Grep-o-i ' [a-f0-9]\{16\} ') && echo $taskid "% (host, port) dbgmsg + =" \n\t$ curl-h \ "Content-type:applicati on/json\ "-x post-d ' {\" url\ ": \" http://testphp.vulnweb.com/artists.php?artist=1\ "} ' http://%s:%d/scan/$taskid/ Start "% (host, port) dbgmsg + =" \n\t$ Curl http://%s:%d/scan/$taskid/data "% (host, port) dbgmsg + =" \n\t$ Curl htt p://%s:%d/scan/$taskid/log "% (host, port) Logger.debug (dbgmsg) addr =" http://%s:%d "% (host, port) Logger.info ( "Starting Rest-json API client to '%s ' ..."% addr) Try: _client (addr) except Exception, Ex:if not ISI Nstance (ex, Urllib2. Httperror) or Ex.code = = Httplib.           Unauthorized: ErrMsg = "There have been a problem while connecting to the" errmsg + = "Rest-json API server at '%s '"% addr ErrMsg + = "(%s)"% ex logger.critical (errmsg) return

The key code we're looking at is

    dbgMsg = "Example client access from command line:"    dbgMsg += "\n\t$ taskid=$(curl http://%s:%d/task/new 2>1 | grep -o -I ‘[a-f0-9]\{16\}‘) && echo $taskid" % (host, port)    dbgMsg += "\n\t$ curl -H \"Content-Type: application/json\" -X POST -d ‘{\"url\": \"http://testphp.vulnweb.com/artists.php?artist=1\"}‘ http://%s:%d/scan/$taskid/start" % (host, port)    dbgMsg += "\n\t$ curl http://%s:%d/scan/$taskid/data" % (host, port)    dbgMsg += "\n\t$ curl http://%s:%d/scan/$taskid/log" % (host, port)    logger.debug(dbgMsg)

In Dbgmsg + = "\n\t$ curl-h \" content-type:application/json\ "-x post-d ' {\" url\ ": \" HTTP://TESTPHP.VULNWEB.COM/ARTISTS.P Hp?artist=1\ "} ' http://%s:%d/scan/$taskid/start"% (host, port) This line of code indicates that a task scan is turned on, content-type:application/ JSON is the part of the request header, the http://%s:%d/scan/$taskid/start specific task that is opened, the -X POST -d ‘{\"url\": \"http://testphp.vulnweb.com/artists.php?artist=1\"}‘ POST request parameter, where only the URL, there is no data parameter about the POST request, so SQLMAPAPI can only perform a GET request for SQL injection detection.

0x02 inherited Ihttplistener Interface (method one), defective

First on the source code:

From burp import iburpextenderfrom burp import ihttplistenerfrom java.io import printwriterimport reimport urllibimport ur Llib2import timeimport jsonfrom Threading Import Threadimport requestsclass Burpextender (IBurpExtender, IHttpListener)  : # #implement Iburpextender # def registerextendercallbacks (self, callbacks): # Keep a reference to Our callbacks Object self._callbacks = callbacks # Set our extension name Callbacks.setextensionname ("Fanyingjie") # obtain our output stream self._stdout = PrintWriter (Callbacks.getstdout (), True) sel F._helpers = Callbacks.gethelpers () # Register ourselves as an Callbacks.registerhttplistener (self) def Processhttpmessage (Self,toolflag,messageisrequest, Messageinfo): if (messageisrequest): A=SELF._HELPERS.A Nalyzerequest (Messageinfo) Method=a.getmethod () Url=str (A.geturl ()) if (("?" in URL) and (            method== "GET"):    Self._stdout.println ("Start") T=autosqli (Target=url,stdout=self._stdout,method=method) t         . Run () class Autosqli (Thread): def __init__ (self,target,stdout,method): self.server= "http://192.168.159.134:8775" Self.taskid = ' Self.target=target self.method=method self._stdout=stdout Self.start_ Time = Time.time () def task_new (self): Self.taskid = Json.loads (Urllib2.urlopen (self.server + '/task/new '). Read (            ) [' TaskID '] self._stdout.println (' Created New task: ' + self.taskid) If Len (Self.taskid) > 0: Return True return False def task_delete (self): if Json.loads (Urllib2.urlopen (self.server + '/task/' +            Self.taskid + '/delete '). Read ()) [' Success ']: Self._stdout.println (' [%s] Deleted task '% (Self.taskid)) Return True return False def scan_start (self): headers = {' Content-type ': ' Application/json '} p ayload = {' URL ': Self.tarGet} URL = self.server + '/scan/' + self.taskid + '/start ' #t = json.loads (requests.post (URL, data=json.dump S (payload), headers=headers). Text) Req=urllib2. Request (Url,data=json.dumps (payload), headers=headers) t=json.loads (Urllib2.urlopen (req). Read ()) Self._stdout . println ("start" + self.taskid) If Len (str (t[' Engineid ')) > 0 and t[' success ']: return True R Eturn False def scan_status (self): status = Json.loads (Urllib2.urlopen (self.server + '/scan/' + self.taskid + '/            Status '). Read ()) [' Status '] if status = = ' running ': return ' running ' if status = = ' terminated ': Return ' terminated ' return ' ERROR ' def scan_data (self): data = Json.loads (Urllib2.urlopen (SELF.S erver + '/scan/' + self.taskid + '/data '). Read ()) [' Data '] if len (data) = = 0:self._stdout.println (' Not I Njection:\t ' + self.target) return False Else:self._stdout.priNtln (' injection:\t ' + self.target) return True def Scan_kill (self): Json.loads (the Rurllib2.urlopen (self). Server + '/scan/' + self.taskid + '/kill '). Read ()) [' Success '] self._stdout.println ("%s Kill")% (Self.taskid) def        Scan_stop (self): Json.loads (Urllib2.urlopen (self.server + '/scan/' + self.taskid + '/stop '). Read ()) [' Success ']                Self._stdout.println ("%s stop")% (Self.taskid) def run (self): Try:if not Self.task_new ():                return False if not Self.scan_start (): Return False while True: If self.scan_status () = = ' Running ': Time.sleep (Ten) elif self.scan_status () = = ' Terminat Ed ': Break else:break #print self.target + ": \ T" + St R (Time.time ()-Self.start_time) if Time.time ()-Self.start_time > 500:self.scan_st                    OP ()Self.scan_kill () Break Self.scan_data () #self. Task_delete () except Excepti On as E:pass

In this plug-in inherits the Ihttplistener interface, after inheriting the interface, every click of the link will be executed once the plug-in, only when the plug-in completed execution, the next step:

Once the link has been accessed, the browser waits for a response, and the method of inheriting the Ihttplistener interface affects the efficiency of the test, but the advantage is that it can check for the presence of injected links
The following is a brief explanation of the code:

        if(messageIsRequest):  #当包是请求包时执行sql injection检查            a=self._helpers.analyzeRequest(messageInfo)  #这是burp提供的一个函数,可以从请求包中获取到url method header等            method=a.getMethod()            url=str(a.getUrl())            if(("?" in url) and (method=="GET")): #当请求是get请求和链接中存在参数时进行sql injection 检查                self._stdout.println("start")                t=AutoSqli(target=url,stdout=self._stdout,method=method)                t.run()
Class Autosqli (Thread): def __init__ (self,target,stdout,method): self.server= "http://192.168.159.134:8775" #开启sq        LMAPAPI Service IP self.taskid = ' self.target=target self.method=method self._stdout=stdout Self.start_time = Time.time () def task_new (self): #创建一个新的任务, and get taskid Self.taskid = Json.loads (Urllib2.urlopen (s Elf.server + '/task/new '). Read ()) [' TaskID '] self._stdout.println (' Created New task: ' + self.taskid ') If Len (self.taskid) > 0:return True return False def task_delete (self): #通过taskid删除某一个任务 if JSON. Loads (Urllib2.urlopen (self.server + '/task/' + self.taskid + '/delete '). Read ()) [' Success ']: Self._stdout.printl N (' [%s] Deleted task '% (self.taskid)) return True return False def scan_start (self): #开始一个扫描, pass in the ground that needs to be scanned Address headers = {' Content-type ': ' Application/json '} payload = {' URL ': self.target} url = self.server + '/ scan/' + Self.taskid + '/start ' #t = json.loads (requests.post (URL, data=json.dumps (payload), headers=headers). Text) Req=urllib2. Request (Url,data=json.dumps (payload), headers=headers) t=json.loads (Urllib2.urlopen (req). Read ()) Self._stdout . println ("start" + self.taskid) If Len (str (t[' Engineid ')) > 0 and t[' success ']: return True R Eturn False def scan_status (self): #查看是否扫描完成, judging by status, terminated is the scan complete status = Json.loads (self.        Server + '/scan/' + self.taskid + '/status '). Read ()) [' Status '] if status = = ' running ': return ' running ' If status = = ' terminated ': return ' terminated ' return ' ERROR ' def scan_data (self): #获取扫描完成的结果, as data = Json.loads (Urllib2.urlopen (self.server + '/scan/' + self.taskid + '/data '). Read ()) [' Data        ' If Len (data) = = 0:self._stdout.println (' not injection:\t ' + self.target) return False else:self._sTdout.println (' injection:\t ' + self.target) return True def Scan_kill (self): Json.loads (Rurllib2.urlo Pen (self.server + '/scan/' + self.taskid + '/kill '). Read ()) [' Success '] self._stdout.println ("%s Kill")% (self.taskid ) def scan_stop (self): Json.loads (Urllib2.urlopen (self.server + '/scan/' + self.taskid + '/stop '). Read ()) [' Succe                 SS '] Self._stdout.println ("%s stop")% (Self.taskid) def run (self): Try:if not Self.task_new ():                return False if not Self.scan_start (): Return False while True: If self.scan_status () = = ' Running ': Time.sleep (Ten) elif self.scan_status () = = ' Terminated ': Break else:break #print Self.target + " : \ t "+ str (time.time ()-Self.start_time) if Time.time ()-Self.start_time > 500:sel           F.scan_stop ()         Self.scan_kill () Break Self.scan_data () #self. Task_delete () excep T Exception as E:pass
In the next article, I will record the second method, can still effectively check out the injection without affecting the efficiency of the test, in the premise of setting some Sqlmapapi parameters, compare the Sqlmapapi and Burpsuite scanner module that more efficient.

Read the Sqlmap source code and write the Burpsuite plugin--sqlmapapi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.