55See the file 'LICENSE' for copying permission
66"""
77
8+ import base64
89import binascii
910import codecs
1011import collections
4748from extra .cloak .cloak import decloak
4849from extra .safe2bin .safe2bin import safecharencode
4950from lib .core .bigarray import BigArray
51+ from lib .core .compat import cmp
52+ from lib .core .compat import round
5053from lib .core .compat import xrange
5154from lib .core .convert import base64pickle
5255from lib .core .convert import base64unpickle
179182from thirdparty .six .moves import configparser as _configparser
180183from thirdparty .six .moves import http_client as _http_client
181184from thirdparty .six .moves import input as _input
185+ from thirdparty .six .moves import reload_module as _reload_module
182186from thirdparty .six .moves import urllib as _urllib
187+ from thirdparty .six .moves import zip as _zip
183188from thirdparty .termcolor .termcolor import colored
184189
185190class UnicodeRawConfigParser (_configparser .RawConfigParser ):
@@ -610,7 +615,7 @@ def paramToDict(place, parameters=None):
610615 if parameter in (conf .base64Parameter or []):
611616 try :
612617 oldValue = value
613- value = value . decode ( "base64" )
618+ value = decodeBase64 ( value , binary = False )
614619 parameters = re .sub (r"\b%s\b" % re .escape (oldValue ), value , parameters )
615620 except :
616621 errMsg = "parameter '%s' does not contain " % parameter
@@ -2278,7 +2283,7 @@ def getFileItems(filename, commentPrefix='#', unicoded=True, lowercase=False, un
22782283
22792284 try :
22802285 with openFile (filename , 'r' , errors = "ignore" ) if unicoded else open (filename , 'r' ) as f :
2281- for line in ( f . readlines () if unicoded else f . xreadlines ()): # xreadlines doesn't return unicode strings when codec.open() is used
2286+ for line in f :
22822287 if commentPrefix :
22832288 if line .find (commentPrefix ) != - 1 :
22842289 line = line [:line .find (commentPrefix )]
@@ -2452,15 +2457,39 @@ def getUnicode(value, encoding=None, noneToNull=False):
24522457 except UnicodeDecodeError :
24532458 return six .text_type (str (value ), errors = "ignore" ) # encoding ignored for non-basestring instances
24542459
2455- def decodeHex (value ):
2460+ def decodeHex (value , binary = True ):
24562461 """
2457- Returns byte representation of provided hexadecimal value
2462+ Returns a decoded representation of provided hexadecimal value
24582463
24592464 >>> decodeHex("313233") == b"123"
24602465 True
2466+ >>> decodeHex("313233", binary=False) == u"123"
2467+ True
2468+ """
2469+
2470+ retVal = codecs .decode (value , "hex" )
2471+
2472+ if not binary :
2473+ retVal = getUnicode (retVal )
2474+
2475+ return retVal
2476+
2477+ def decodeBase64 (value , binary = True ):
2478+ """
2479+ Returns a decoded representation of provided Base64 value
2480+
2481+ >>> decodeBase64("MTIz") == b"123"
2482+ True
2483+ >>> decodeBase64("MTIz", binary=False) == u"123"
2484+ True
24612485 """
24622486
2463- return bytes .fromhex (getUnicode (value )) if hasattr (bytes , "fromhex" ) else value .decode ("hex" )
2487+ retVal = base64 .b64decode (value )
2488+
2489+ if not binary :
2490+ retVal = getUnicode (retVal )
2491+
2492+ return retVal
24642493
24652494def getBytes (value , encoding = UNICODE_ENCODING , errors = "strict" ):
24662495 """
@@ -2475,7 +2504,7 @@ def getBytes(value, encoding=UNICODE_ENCODING, errors="strict"):
24752504 if isinstance (value , six .text_type ):
24762505 if INVALID_UNICODE_PRIVATE_AREA :
24772506 for char in xrange (0xF0000 , 0xF00FF + 1 ):
2478- value = value .replace (unichr (char ), "%s%02x" % (SAFE_HEX_MARKER , char - 0xF0000 ))
2507+ value = value .replace (six . unichr (char ), "%s%02x" % (SAFE_HEX_MARKER , char - 0xF0000 ))
24792508
24802509 retVal = value .encode (encoding , errors )
24812510 retVal = re .sub (r"%s([0-9a-f]{2})" % SAFE_HEX_MARKER , lambda _ : decodeHex (_ .group (1 )), retVal )
@@ -2525,7 +2554,13 @@ def longestCommonPrefix(*sequences):
25252554 return sequences [0 ]
25262555
25272556def commonFinderOnly (initial , sequence ):
2528- return longestCommonPrefix (* filter (lambda _ : _ .startswith (initial ), sequence ))
2557+ """
2558+ Returns parts of sequence which start with the given initial string
2559+
2560+ >>> commonFinderOnly("abcd", ["abcdefg", "foobar", "abcde"])
2561+ ['abcdefg', 'abcde']
2562+ """
2563+ return longestCommonPrefix ([_ for _ in sequence if _ .startswith (initial )])
25292564
25302565def pushValue (value ):
25312566 """
@@ -2811,13 +2846,13 @@ def runningAsAdmin():
28112846 if PLATFORM in ("posix" , "mac" ):
28122847 _ = os .geteuid ()
28132848
2814- isAdmin = isinstance (_ , (int , float , long )) and _ == 0
2849+ isAdmin = isinstance (_ , (float , six . integer_types )) and _ == 0
28152850 elif IS_WIN :
28162851 import ctypes
28172852
28182853 _ = ctypes .windll .shell32 .IsUserAnAdmin ()
28192854
2820- isAdmin = isinstance (_ , (int , float , long )) and _ == 1
2855+ isAdmin = isinstance (_ , (float , six . integer_types )) and _ == 1
28212856 else :
28222857 errMsg = "sqlmap is not able to check if you are running it "
28232858 errMsg += "as an administrator account on this platform. "
@@ -3318,6 +3353,8 @@ def unArrayizeValue(value):
33183353
33193354 >>> unArrayizeValue(['1'])
33203355 '1'
3356+ >>> unArrayizeValue(['1', '2'])
3357+ '1'
33213358 """
33223359
33233360 if isListLike (value ):
@@ -3326,8 +3363,8 @@ def unArrayizeValue(value):
33263363 elif len (value ) == 1 and not isListLike (value [0 ]):
33273364 value = value [0 ]
33283365 else :
3329- _ = filter ( lambda _ : _ is not None , ( _ for _ in flattenValue (value )))
3330- value = _ [0 ] if len (_ ) > 0 else None
3366+ value = [ _ for _ in flattenValue (value ) if _ is not None ]
3367+ value = value [0 ] if len (value ) > 0 else None
33313368
33323369 return value
33333370
@@ -3459,7 +3496,7 @@ def decodeIntToUnicode(value):
34593496 elif Backend .isDbms (DBMS .MSSQL ):
34603497 retVal = getUnicode (raw , "UTF-16-BE" )
34613498 elif Backend .getIdentifiedDbms () in (DBMS .PGSQL , DBMS .ORACLE ):
3462- retVal = unichr (value )
3499+ retVal = six . unichr (value )
34633500 else :
34643501 retVal = getUnicode (raw , conf .encoding )
34653502 else :
@@ -3600,7 +3637,7 @@ def createGithubIssue(errMsg, excMsg):
36003637 choice = None
36013638
36023639 if choice :
3603- ex = None
3640+ _excMsg = None
36043641 errMsg = errMsg [errMsg .find ("\n " ):]
36053642
36063643 req = _urllib .request .Request (url = "https://api.github.com/search/issues?q=%s" % _urllib .parse .quote ("repo:sqlmapproject/sqlmap Unhandled exception (#%s)" % key ))
@@ -3621,12 +3658,13 @@ def createGithubIssue(errMsg, excMsg):
36213658 pass
36223659
36233660 data = {"title" : "Unhandled exception (#%s)" % key , "body" : "```%s\n ```\n ```\n %s```" % (errMsg , excMsg )}
3624- req = _urllib .request .Request (url = "https://api.github.com/repos/sqlmapproject/sqlmap/issues" , data = json .dumps (data ), headers = {"Authorization" : "token %s" % GITHUB_REPORT_OAUTH_TOKEN . decode ( "base64" )})
3661+ req = _urllib .request .Request (url = "https://api.github.com/repos/sqlmapproject/sqlmap/issues" , data = json .dumps (data ), headers = {"Authorization" : "token %s" % decodeBase64 ( GITHUB_REPORT_OAUTH_TOKEN , binary = False )})
36253662
36263663 try :
36273664 content = _urllib .request .urlopen (req ).read ()
36283665 except Exception as ex :
36293666 content = None
3667+ _excMsg = getSafeExString (ex )
36303668
36313669 issueUrl = re .search (r"https://github.com/sqlmapproject/sqlmap/issues/\d+" , content or "" )
36323670 if issueUrl :
@@ -3640,8 +3678,8 @@ def createGithubIssue(errMsg, excMsg):
36403678 pass
36413679 else :
36423680 warnMsg = "something went wrong while creating a Github issue"
3643- if ex :
3644- warnMsg += " ('%s')" % getSafeExString ( ex )
3681+ if _excMsg :
3682+ warnMsg += " ('%s')" % _excMsg
36453683 if "Unauthorized" in warnMsg :
36463684 warnMsg += ". Please update to the latest revision"
36473685 logger .warn (warnMsg )
@@ -4403,7 +4441,7 @@ def checkSystemEncoding():
44034441 warnMsg = "temporary switching to charset 'cp1256'"
44044442 logger .warn (warnMsg )
44054443
4406- reload (sys )
4444+ _reload_module (sys )
44074445 sys .setdefaultencoding ("cp1256" )
44084446
44094447def evaluateCode (code , variables = None ):
@@ -4741,7 +4779,7 @@ def splitFields(fields, delimiter=','):
47414779 commas .extend (zeroDepthSearch (fields , ',' ))
47424780 commas = sorted (commas )
47434781
4744- return [fields [x + 1 :y ] for (x , y ) in zip (commas , commas [1 :])]
4782+ return [fields [x + 1 :y ] for (x , y ) in _zip (commas , commas [1 :])]
47454783
47464784def pollProcess (process , suppress_errors = False ):
47474785 """
@@ -4807,7 +4845,7 @@ def _parseBurpLog(content):
48074845 for match in re .finditer (BURP_XML_HISTORY_REGEX , content , re .I | re .S ):
48084846 port , request = match .groups ()
48094847 try :
4810- request = request . decode ( "base64" )
4848+ request = decodeBase64 ( request , binary = False )
48114849 except binascii .Error :
48124850 continue
48134851 _ = re .search (r"%s:.+" % re .escape (HTTP_HEADER .HOST ), request )
0 commit comments