Skip to content

Commit edc6f47

Browse files
committed
Some refactoring
1 parent bb6e8fd commit edc6f47

File tree

19 files changed

+88
-93
lines changed

19 files changed

+88
-93
lines changed

lib/controller/checks.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@
1010
import random
1111
import re
1212
import socket
13+
import subprocess
1314
import time
1415

15-
from subprocess import Popen as execute
16-
1716
from extra.beep.beep import beep
1817
from lib.core.agent import agent
1918
from lib.core.common import Backend
@@ -200,7 +199,7 @@ def checkSqlInjection(place, parameter, value):
200199
if conf.tech and isinstance(conf.tech, list) and stype not in conf.tech:
201200
debugMsg = "skipping test '%s' because the user " % title
202201
debugMsg += "specified to test only for "
203-
debugMsg += "%s techniques" % " & ".join(map(lambda x: PAYLOAD.SQLINJECTION[x], conf.tech))
202+
debugMsg += "%s techniques" % " & ".join(PAYLOAD.SQLINJECTION[_] for _ in conf.tech)
204203
logger.debug(debugMsg)
205204
continue
206205

@@ -651,20 +650,20 @@ def genCmpPayload():
651650

652651
# Feed with test details every time a test is successful
653652
if hasattr(test, "details"):
654-
for dKey, dValue in test.details.items():
655-
if dKey == "dbms":
656-
injection.dbms = dValue
653+
for key, value in test.details.items():
654+
if key == "dbms":
655+
injection.dbms = value
657656

658-
if not isinstance(dValue, list):
659-
Backend.setDbms(dValue)
657+
if not isinstance(value, list):
658+
Backend.setDbms(value)
660659
else:
661-
Backend.forceDbms(dValue[0], True)
660+
Backend.forceDbms(value[0], True)
662661

663-
elif dKey == "dbms_version" and injection.dbms_version is None and not conf.testFilter:
664-
injection.dbms_version = Backend.setVersion(dValue)
662+
elif key == "dbms_version" and injection.dbms_version is None and not conf.testFilter:
663+
injection.dbms_version = Backend.setVersion(value)
665664

666-
elif dKey == "os" and injection.os is None:
667-
injection.os = Backend.setOs(dValue)
665+
elif key == "os" and injection.os is None:
666+
injection.os = Backend.setOs(value)
668667

669668
if vector is None and "vector" in test and test.vector is not None:
670669
vector = test.vector
@@ -696,7 +695,7 @@ def genCmpPayload():
696695
infoMsg = "executing alerting shell command(s) ('%s')" % conf.alert
697696
logger.info(infoMsg)
698697

699-
process = execute(conf.alert, shell=True)
698+
process = subprocess.Popen(conf.alert, shell=True)
700699
process.wait()
701700

702701
kb.alerted = True
@@ -921,8 +920,10 @@ def heuristicCheckSqlInjection(place, parameter):
921920

922921
origValue = conf.paramDict[place][parameter]
923922
paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else place
923+
924924
prefix = ""
925925
suffix = ""
926+
randStr = ""
926927

927928
if conf.prefix or conf.suffix:
928929
if conf.prefix:
@@ -931,8 +932,6 @@ def heuristicCheckSqlInjection(place, parameter):
931932
if conf.suffix:
932933
suffix = conf.suffix
933934

934-
randStr = ""
935-
936935
while randStr.count('\'') != 1 or randStr.count('\"') != 1:
937936
randStr = randomStr(length=10, alphabet=HEURISTIC_CHECK_ALPHABET)
938937

lib/controller/controller.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def _showInjections():
165165
if hasattr(conf, "api"):
166166
conf.dumper.string("", kb.injections, content_type=CONTENT_TYPE.TECHNIQUES)
167167
else:
168-
data = "".join(set(map(lambda x: _formatInjection(x), kb.injections))).rstrip("\n")
168+
data = "".join(set(_formatInjection(_) for _ in kb.injections)).rstrip("\n")
169169
conf.dumper.string(header, data)
170170

171171
if conf.tamper:
@@ -224,7 +224,7 @@ def _saveToResultsFile():
224224
return
225225

226226
results = {}
227-
techniques = dict(map(lambda x: (x[1], x[0]), getPublicTypeMembers(PAYLOAD.TECHNIQUE)))
227+
techniques = dict((_[1], _[0]) for _ in getPublicTypeMembers(PAYLOAD.TECHNIQUE))
228228

229229
for injection in kb.injections + kb.falsePositives:
230230
if injection.place is None or injection.parameter is None:
@@ -238,7 +238,7 @@ def _saveToResultsFile():
238238

239239
for key, value in results.items():
240240
place, parameter, notes = key
241-
line = "%s,%s,%s,%s,%s%s" % (safeCSValue(kb.originalUrls.get(conf.url) or conf.url), place, parameter, "".join(map(lambda x: techniques[x][0].upper(), sorted(value))), notes, os.linesep)
241+
line = "%s,%s,%s,%s,%s%s" % (safeCSValue(kb.originalUrls.get(conf.url) or conf.url), place, parameter, "".join(techniques[_][0].upper() for _ in sorted(value)), notes, os.linesep)
242242
conf.resultsFP.writelines(line)
243243

244244
if not results:

lib/core/common.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import re
2424
import socket
2525
import string
26+
import subprocess
2627
import sys
2728
import tempfile
2829
import time
@@ -37,8 +38,6 @@
3738
from difflib import SequenceMatcher
3839
from math import sqrt
3940
from optparse import OptionValueError
40-
from subprocess import PIPE
41-
from subprocess import Popen as execute
4241
from xml.dom import minidom
4342
from xml.sax import parse
4443
from xml.sax import SAXParseException
@@ -1889,7 +1888,7 @@ def getConsoleWidth(default=80):
18891888
FNULL = open(os.devnull, 'w')
18901889
except IOError:
18911890
FNULL = None
1892-
process = execute("stty size", shell=True, stdout=PIPE, stderr=FNULL or PIPE)
1891+
process = subprocess.Popen("stty size", shell=True, stdout=subprocess.PIPE, stderr=FNULL or subprocess.PIPE)
18931892
stdout, _ = process.communicate()
18941893
items = stdout.split()
18951894

lib/core/option.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,17 +1335,17 @@ def _setHTTPAuthentication():
13351335
debugMsg = "setting the HTTP authentication type and credentials"
13361336
logger.debug(debugMsg)
13371337

1338-
aTypeLower = conf.authType.lower()
1338+
authType = conf.authType.lower()
13391339

1340-
if aTypeLower in (AUTH_TYPE.BASIC, AUTH_TYPE.DIGEST):
1340+
if authType in (AUTH_TYPE.BASIC, AUTH_TYPE.DIGEST):
13411341
regExp = "^(.*?):(.*?)$"
1342-
errMsg = "HTTP %s authentication credentials " % aTypeLower
1342+
errMsg = "HTTP %s authentication credentials " % authType
13431343
errMsg += "value must be in format 'username:password'"
1344-
elif aTypeLower == AUTH_TYPE.NTLM:
1344+
elif authType == AUTH_TYPE.NTLM:
13451345
regExp = "^(.*\\\\.*):(.*?)$"
13461346
errMsg = "HTTP NTLM authentication credentials value must "
13471347
errMsg += "be in format 'DOMAIN\username:password'"
1348-
elif aTypeLower == AUTH_TYPE.PKI:
1348+
elif authType == AUTH_TYPE.PKI:
13491349
errMsg = "HTTP PKI authentication require "
13501350
errMsg += "usage of option `--auth-pki`"
13511351
raise SqlmapSyntaxException(errMsg)
@@ -1362,13 +1362,13 @@ def _setHTTPAuthentication():
13621362

13631363
_setAuthCred()
13641364

1365-
if aTypeLower == AUTH_TYPE.BASIC:
1365+
if authType == AUTH_TYPE.BASIC:
13661366
authHandler = SmartHTTPBasicAuthHandler(kb.passwordMgr)
13671367

1368-
elif aTypeLower == AUTH_TYPE.DIGEST:
1368+
elif authType == AUTH_TYPE.DIGEST:
13691369
authHandler = urllib2.HTTPDigestAuthHandler(kb.passwordMgr)
13701370

1371-
elif aTypeLower == AUTH_TYPE.NTLM:
1371+
elif authType == AUTH_TYPE.NTLM:
13721372
try:
13731373
from ntlm import HTTPNtlmAuthHandler
13741374
except ImportError:

lib/core/revision.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@
77

88
import os
99
import re
10-
11-
from subprocess import PIPE
12-
from subprocess import Popen as execute
10+
import subprocess
1311

1412
def getRevisionNumber():
1513
"""
@@ -46,7 +44,7 @@ def getRevisionNumber():
4644
break
4745

4846
if not retVal:
49-
process = execute("git rev-parse --verify HEAD", shell=True, stdout=PIPE, stderr=PIPE)
47+
process = subprocess.Popen("git rev-parse --verify HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
5048
stdout, _ = process.communicate()
5149
match = re.search(r"(?i)[0-9a-f]{32}", stdout or "")
5250
retVal = match.group(0) if match else None

lib/core/settings.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from lib.core.enums import OS
2020

2121
# sqlmap version (<major>.<minor>.<month>.<monthly commit>)
22-
VERSION = "1.0.12.10"
22+
VERSION = "1.0.12.11"
2323
TYPE = "dev" if VERSION.count('.') > 2 and VERSION.split('.')[-1] != '0' else "stable"
2424
TYPE_COLORS = {"dev": 33, "stable": 90, "pip": 34}
2525
VERSION_STRING = "sqlmap/%s#%s" % ('.'.join(VERSION.split('.')[:-1]) if VERSION.count('.') > 2 and VERSION.split('.')[-1] == '0' else VERSION, TYPE)
@@ -527,7 +527,7 @@
527527
UNENCODED_ORIGINAL_VALUE = "original"
528528

529529
# Common column names containing usernames (used for hash cracking in some cases)
530-
COMMON_USER_COLUMNS = ("login", "user", "username", "user_name", "user_login", "benutzername", "benutzer", "utilisateur", "usager", "consommateur", "utente", "utilizzatore", "usufrutuario", "korisnik", "usuario", "consumidor")
530+
COMMON_USER_COLUMNS = ("login", "user", "username", "user_name", "user_login", "benutzername", "benutzer", "utilisateur", "usager", "consommateur", "utente", "utilizzatore", "usufrutuario", "korisnik", "usuario", "consumidor", "client", "cuser")
531531

532532
# Default delimiter in GET/POST values
533533
DEFAULT_GET_POST_DELIMITER = '&'

lib/core/update.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,9 @@
88
import locale
99
import os
1010
import re
11+
import subprocess
1112
import time
1213

13-
from subprocess import PIPE
14-
from subprocess import Popen as execute
15-
1614
from lib.core.common import dataToStdout
1715
from lib.core.common import getSafeExString
1816
from lib.core.common import pollProcess
@@ -44,7 +42,7 @@ def update():
4442
dataToStdout("\r[%s] [INFO] update in progress " % time.strftime("%X"))
4543

4644
try:
47-
process = execute("git checkout . && git pull %s HEAD" % GIT_REPOSITORY, shell=True, stdout=PIPE, stderr=PIPE, cwd=paths.SQLMAP_ROOT_PATH.encode(locale.getpreferredencoding())) # Reference: http://blog.stastnarodina.com/honza-en/spot/python-unicodeencodeerror/
45+
process = subprocess.Popen("git checkout . && git pull %s HEAD" % GIT_REPOSITORY, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=paths.SQLMAP_ROOT_PATH.encode(locale.getpreferredencoding())) # Reference: http://blog.stastnarodina.com/honza-en/spot/python-unicodeencodeerror/
4846
pollProcess(process, True)
4947
stdout, stderr = process.communicate()
5048
success = not process.returncode

lib/request/direct.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ def direct(query, content=True):
6363
elif output:
6464
infoMsg = "resumed: %s..." % getUnicode(output, UNICODE_ENCODING)[:20]
6565
logger.info(infoMsg)
66+
6667
threadData.lastQueryDuration = calculateDeltaSeconds(start)
6768

6869
if not output:

lib/request/inject.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser
364364
if conf.direct:
365365
value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression)
366366

367-
elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))):
367+
elif any(isTechniqueAvailable(_) for _ in getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True)):
368368
query = cleanQuery(expression)
369369
query = expandAsteriskForColumns(query)
370370
value = None

lib/takeover/abstraction.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@
2525
from lib.request import inject
2626
from lib.takeover.udf import UDF
2727
from lib.takeover.web import Web
28-
from lib.takeover.xp_cmdshell import Xp_cmdshell
28+
from lib.takeover.xp_cmdshell import XP_cmdshell
2929

3030

31-
class Abstraction(Web, UDF, Xp_cmdshell):
31+
class Abstraction(Web, UDF, XP_cmdshell):
3232
"""
3333
This class defines an abstraction layer for OS takeover functionalities
34-
to UDF / Xp_cmdshell objects
34+
to UDF / XP_cmdshell objects
3535
"""
3636

3737
def __init__(self):
@@ -40,7 +40,7 @@ def __init__(self):
4040

4141
UDF.__init__(self)
4242
Web.__init__(self)
43-
Xp_cmdshell.__init__(self)
43+
XP_cmdshell.__init__(self)
4444

4545
def execCmd(self, cmd, silent=False):
4646
if self.webBackdoorUrl and not isStackingAvailable():

0 commit comments

Comments
 (0)