Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit dcf7277

Browse files
committed
some more refactorings
1 parent 6632aa7 commit dcf7277

12 files changed

Lines changed: 244 additions & 236 deletions

File tree

lib/core/common.py

Lines changed: 102 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,11 +1192,14 @@ def expandAsteriskForColumns(expression):
11921192

11931193
return expression
11941194

1195-
def getRange(count, dump=False, plusOne=False):
1195+
def getLimitRange(count, dump=False, plusOne=False):
1196+
"""
1197+
Returns range of values used in limit/offset constructs
1198+
"""
1199+
1200+
retVal = None
11961201
count = int(count)
1197-
indexRange = None
1198-
limitStart = 1
1199-
limitStop = count
1202+
limitStart, limitStop = 1, count
12001203

12011204
if dump:
12021205
if isinstance(conf.limitStop, int) and conf.limitStop > 0 and conf.limitStop < limitStop:
@@ -1205,11 +1208,15 @@ def getRange(count, dump=False, plusOne=False):
12051208
if isinstance(conf.limitStart, int) and conf.limitStart > 0 and conf.limitStart <= limitStop:
12061209
limitStart = conf.limitStart
12071210

1208-
indexRange = xrange(limitStart, limitStop + 1) if plusOne else xrange(limitStart - 1, limitStop)
1211+
retVal = xrange(limitStart, limitStop + 1) if plusOne else xrange(limitStart - 1, limitStop)
12091212

1210-
return indexRange
1213+
return retVal
12111214

12121215
def parseUnionPage(output, unique=True):
1216+
"""
1217+
Returns resulting items from inband query inside provided page content
1218+
"""
1219+
12131220
if output is None:
12141221
return None
12151222

@@ -1250,7 +1257,7 @@ def parseUnionPage(output, unique=True):
12501257

12511258
def parseFilePaths(page):
12521259
"""
1253-
Detect (possible) absolute system paths inside the provided page content
1260+
Detects (possible) absolute system paths inside the provided page content
12541261
"""
12551262

12561263
if page:
@@ -1265,32 +1272,6 @@ def parseFilePaths(page):
12651272
if absFilePath not in kb.absFilePaths:
12661273
kb.absFilePaths.add(absFilePath)
12671274

1268-
def getDelayQuery(andCond=False):
1269-
query = None
1270-
1271-
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL):
1272-
if not kb.data.banner:
1273-
conf.dbmsHandler.getVersionFromBanner()
1274-
1275-
banVer = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None
1276-
1277-
if banVer is None or (Backend.isDbms(DBMS.MYSQL) and banVer >= "5.0.12") or (Backend.isDbms(DBMS.PGSQL) and banVer >= "8.2"):
1278-
query = queries[Backend.getIdentifiedDbms()].timedelay.query % conf.timeSec
1279-
else:
1280-
query = queries[Backend.getIdentifiedDbms()].timedelay.query2 % conf.timeSec
1281-
elif Backend.isDbms(DBMS.FIREBIRD):
1282-
query = queries[Backend.getIdentifiedDbms()].timedelay.query
1283-
else:
1284-
query = queries[Backend.getIdentifiedDbms()].timedelay.query % conf.timeSec
1285-
1286-
if andCond:
1287-
if Backend.getIdentifiedDbms() in ( DBMS.MYSQL, DBMS.SQLITE ):
1288-
query = query.replace("SELECT ", "")
1289-
elif Backend.isDbms(DBMS.FIREBIRD):
1290-
query = "(%s)>0" % query
1291-
1292-
return query
1293-
12941275
def getLocalIP():
12951276
retVal = None
12961277
try:
@@ -1310,11 +1291,11 @@ def getRemoteIP():
13101291

13111292
def getFileType(filePath):
13121293
try:
1313-
magicFileType = magic.from_file(filePath)
1294+
_ = magic.from_file(filePath)
13141295
except:
13151296
return "unknown"
13161297

1317-
return "text" if "ASCII" in magicFileType or "text" in magicFileType else "binary"
1298+
return "text" if "ASCII" in _ or "text" in _ else "binary"
13181299

13191300
def getCharset(charsetType=None):
13201301
asciiTbl = []
@@ -1354,15 +1335,14 @@ def getCharset(charsetType=None):
13541335

13551336
return asciiTbl
13561337

1357-
def searchEnvPath(fileName):
1358-
envPaths = os.environ["PATH"]
1338+
def searchEnvPath(filename):
13591339
result = None
1340+
path = os.environ.get("PATH", "")
1341+
paths = path.split(";") if IS_WIN else path.split(":")
13601342

1361-
envPaths = envPaths.split(";") if IS_WIN else envPaths.split(":")
1362-
1363-
for envPath in envPaths:
1364-
envPath = envPath.replace(";", "")
1365-
result = os.path.exists(os.path.normpath(os.path.join(envPath, fileName)))
1343+
for _ in paths:
1344+
_ = _.replace(";", "")
1345+
result = os.path.exists(os.path.normpath(os.path.join(_, filename)))
13661346

13671347
if result:
13681348
break
@@ -1394,28 +1374,40 @@ def urlEncodeCookieValues(cookieStr):
13941374
else:
13951375
return None
13961376

1397-
def directoryPath(path):
1377+
def directoryPath(filepath):
1378+
"""
1379+
Returns directory path for a given filepath
1380+
"""
1381+
13981382
retVal = None
13991383

1400-
if isWindowsDriveLetterPath(path):
1401-
retVal = ntpath.dirname(path)
1384+
if isWindowsDriveLetterPath(filepath):
1385+
retVal = ntpath.dirname(filepath)
14021386
else:
1403-
retVal = posixpath.dirname(path)
1387+
retVal = posixpath.dirname(filepath)
14041388

14051389
return retVal
14061390

1407-
def normalizePath(path):
1391+
def normalizePath(filepath):
1392+
"""
1393+
Returns normalized string representation of a given filepath
1394+
"""
1395+
14081396
retVal = None
14091397

1410-
if isWindowsDriveLetterPath(path):
1411-
retVal = ntpath.normpath(path)
1398+
if isWindowsDriveLetterPath(filepath):
1399+
retVal = ntpath.normpath(filepath)
14121400
else:
1413-
retVal = posixpath.normpath(path)
1401+
retVal = posixpath.normpath(filepath)
14141402

14151403
return retVal
14161404

1417-
def safeStringFormat(formatStr, params):
1418-
retVal = formatStr.replace("%d", "%s")
1405+
def safeStringFormat(format_, params):
1406+
"""
1407+
Avoids problems with inappropriate string format strings
1408+
"""
1409+
1410+
retVal = format_.replace("%d", "%s")
14191411

14201412
if isinstance(params, basestring):
14211413
retVal = retVal.replace("%s", params)
@@ -1435,23 +1427,12 @@ def safeStringFormat(formatStr, params):
14351427

14361428
return retVal
14371429

1438-
def sanitizeAsciiString(subject):
1439-
if subject:
1440-
index = None
1441-
1442-
for i in xrange(len(subject)):
1443-
if ord(subject[i]) >= 128:
1444-
index = i
1445-
break
1446-
1447-
if index is None:
1448-
return subject
1449-
else:
1450-
return subject[:index] + "".join(subject[i] if ord(subject[i]) < 128 else '?' for i in xrange(index, len(subject)))
1451-
else:
1452-
return None
1453-
14541430
def getFilteredPageContent(page, onlyText=True):
1431+
"""
1432+
Returns filtered page content without script, style and/or comments
1433+
or all HTML tags
1434+
"""
1435+
14551436
retVal = page
14561437

14571438
# only if the page's charset has been successfully identified
@@ -2402,6 +2383,10 @@ def isTechniqueAvailable(technique):
24022383
return getTechniqueData(technique) is not None
24032384

24042385
def isInferenceAvailable():
2386+
"""
2387+
Returns True whether techniques using inference technique are available
2388+
"""
2389+
24052390
return any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.BOOLEAN, PAYLOAD.TECHNIQUE.STACKED, PAYLOAD.TECHNIQUE.TIME))
24062391

24072392
def setOptimize():
@@ -2619,7 +2604,7 @@ def listToStrValue(value):
26192604
def getExceptionFrameLocals():
26202605
"""
26212606
Returns dictionary with local variable content from frame
2622-
where exception was raised
2607+
where exception has been raised
26232608
"""
26242609

26252610
retVal = {}
@@ -2793,7 +2778,7 @@ def isNullValue(value):
27932778

27942779
def expandMnemonics(mnemonics, parser, args):
27952780
"""
2796-
Expand mnemonic options
2781+
Expands mnemonic options
27972782
"""
27982783

27992784
class MnemonicNode:
@@ -2876,7 +2861,7 @@ def __init__(self):
28762861

28772862
def safeCSValue(value):
28782863
"""
2879-
Returns value safe for CSV dumping.
2864+
Returns value safe for CSV dumping
28802865
Reference: http://tools.ietf.org/html/rfc4180
28812866
"""
28822867

@@ -2890,6 +2875,10 @@ def safeCSValue(value):
28902875
return retVal
28912876

28922877
def filterPairValues(values):
2878+
"""
2879+
Returns only list-like values with length 2
2880+
"""
2881+
28932882
retVal = []
28942883

28952884
if not isNoneValue(values) and hasattr(values, '__iter__'):
@@ -2973,6 +2962,10 @@ def quote(s, safe):
29732962
return urlparse.urlunsplit([parts.scheme, netloc, path, query, parts.fragment])
29742963

29752964
def findPageForms(content, url, raise_=False, addToTargets=False):
2965+
"""
2966+
Parses given page content for possible forms
2967+
"""
2968+
29762969
class _(StringIO):
29772970
def __init__(self, content, url):
29782971
StringIO.__init__(self, unicodeencode(content, kb.pageEncoding) if isinstance(content, unicode) else content)
@@ -3016,15 +3009,18 @@ def geturl(self):
30163009
if not item.selected:
30173010
item.selected = True
30183011
break
3012+
30193013
request = form.click()
30203014
url = urldecode(request.get_full_url(), kb.pageEncoding)
30213015
method = request.get_method()
30223016
data = request.get_data() if request.has_data() else None
30233017
data = urldecode(data, kb.pageEncoding) if data and urlencode(DEFAULT_GET_POST_DELIMITER, None) not in data else data
3018+
30243019
if not data and method and method.upper() == HTTPMETHOD.POST:
30253020
debugMsg = "invalid POST form with blank data detected"
30263021
logger.debug(debugMsg)
30273022
continue
3023+
30283024
target = (url, method, data, conf.cookie)
30293025
retVal.add(target)
30303026
else:
@@ -3041,36 +3037,62 @@ def geturl(self):
30413037
return retVal
30423038

30433039
def getHostHeader(url):
3040+
"""
3041+
Returns proper Host header value for a given target URL
3042+
"""
3043+
30443044
retVal = urlparse.urlparse(url).netloc
30453045

30463046
if any(retVal.endswith(':%d' % _) for _ in [80, 443]):
30473047
retVal = retVal.split(':')[0]
30483048

30493049
return retVal
30503050

3051-
def executeCode(code, variables=None):
3051+
def evaluateCode(code, variables=None):
3052+
"""
3053+
Executes given python code given in a string form
3054+
"""
3055+
30523056
try:
30533057
exec(code, variables)
30543058
except Exception, ex:
30553059
errMsg = "an error occured while evaluating provided code ('%s'). " % ex
30563060
raise sqlmapGenericException, errMsg
30573061

30583062
def serializeObject(object_):
3063+
"""
3064+
Serializes given object
3065+
"""
3066+
30593067
return pickle.dumps(object_)
30603068

30613069
def unserializeObject(value):
3070+
"""
3071+
Unserializes object from given serialized form
3072+
"""
3073+
30623074
retVal = None
30633075
if value:
30643076
retVal = pickle.loads(value.encode(UNICODE_ENCODING)) # pickle has problems with Unicode
30653077
return retVal
30663078

3067-
def resetCounter(counter):
3068-
kb.counters[counter] = 0
3079+
def resetCounter(technique):
3080+
"""
3081+
Resets query counter for a given technique
3082+
"""
3083+
3084+
kb.counters[technique] = 0
3085+
3086+
def incrementCounter(technique):
3087+
"""
3088+
Increments query counter for a given technique
3089+
"""
3090+
3091+
kb.counters[technique] = getCounter(technique) + 1
30693092

3070-
def incrementCounter(counter):
3071-
if counter not in kb.counters:
3072-
resetCounter(counter)
3073-
kb.counters[counter] += 1
3093+
def getCounter(technique):
3094+
"""
3095+
Returns query counter for a given technique
3096+
"""
30743097

3075-
def getCounter(counter):
3076-
return kb.counters.get(counter, 0)
3098+
return kb.counters.get(technique, 0)

0 commit comments

Comments
 (0)