This commit is contained in:
Levi Gross 2012-12-05 12:42:59 -08:00
commit 9674c52e3b
139 changed files with 1715 additions and 2512 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
*.py[cod] *.py[cod]
output/ output/
.sqlmap_history .sqlmap_history
.idea/

View File

@ -4,5 +4,3 @@
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -13,54 +13,21 @@ import socket
import time import time
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import arrayizeValue from lib.core.common import arrayizeValue, Backend, beep, extractRegexResult, extractTextTagContent, \
from lib.core.common import Backend findDynamicContent, Format, getLastRequestHTTPError, getSortedInjectionTests, getUnicode, intersect, \
from lib.core.common import beep listToStrValue, parseFilePaths, popValue, pushValue, randomInt, randomStr, readInput, showStaticWords, \
from lib.core.common import extractRegexResult singleTimeLogMessage, singleTimeWarnMessage, wasLastRequestDBMSError, wasLastRequestHTTPError
from lib.core.common import extractTextTagContent
from lib.core.common import findDynamicContent from lib.core.data import conf, kb, logger
from lib.core.common import Format
from lib.core.common import getComparePageRatio from lib.core.datatype import AttribDict, InjectionDict
from lib.core.common import getLastRequestHTTPError from lib.core.enums import HEURISTIC_TEST, HTTPHEADER, HTTPMETHOD, NULLCONNECTION, PAYLOAD, PLACE
from lib.core.common import getSortedInjectionTests
from lib.core.common import getUnicode from lib.core.exception import sqlmapConnectionException, sqlmapNoneDataException, sqlmapSilentQuitException ,\
from lib.core.common import intersect sqlmapUserQuitException
from lib.core.common import listToStrValue from lib.core.settings import UPPER_RATIO_BOUND, FORMAT_EXCEPTION_STRINGS, HEURISTIC_CHECK_ALPHABET, \
from lib.core.common import parseFilePaths SUHOSHIN_MAX_VALUE_LENGTH, UNKNOWN_DBMS_VERSION, LOWER_RATIO_BOUND, IDS_WAF_CHECK_PAYLOAD
from lib.core.common import popValue
from lib.core.common import pushValue
from lib.core.common import randomInt
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.common import showStaticWords
from lib.core.common import singleTimeLogMessage
from lib.core.common import singleTimeWarnMessage
from lib.core.common import wasLastRequestDBMSError
from lib.core.common import wasLastRequestHTTPError
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.datatype import AttribDict
from lib.core.datatype import InjectionDict
from lib.core.enums import HEURISTIC_TEST
from lib.core.enums import HTTPHEADER
from lib.core.enums import HTTPMETHOD
from lib.core.enums import NULLCONNECTION
from lib.core.enums import PAYLOAD
from lib.core.enums import PLACE
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapNoneDataException
from lib.core.exception import sqlmapSilentQuitException
from lib.core.exception import sqlmapUserQuitException
from lib.core.settings import CONSTANT_RATIO
from lib.core.settings import FORMAT_EXCEPTION_STRINGS
from lib.core.settings import HEURISTIC_CHECK_ALPHABET
from lib.core.settings import SUHOSHIN_MAX_VALUE_LENGTH
from lib.core.settings import UNKNOWN_DBMS_VERSION
from lib.core.settings import LOWER_RATIO_BOUND
from lib.core.settings import UPPER_RATIO_BOUND
from lib.core.settings import IDS_WAF_CHECK_PAYLOAD
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request
from lib.request.inject import checkBooleanExpression from lib.request.inject import checkBooleanExpression

View File

@ -9,55 +9,21 @@ import os
import re import re
from lib.controller.action import action from lib.controller.action import action
from lib.controller.checks import checkSqlInjection from lib.controller.checks import checkSqlInjection, checkDynParam, checkStability, checkString, checkRegexp, \
from lib.controller.checks import checkDynParam checkConnection, checkNullConnection, checkWaf, heuristicCheckSqlInjection
from lib.controller.checks import checkStability
from lib.controller.checks import checkString
from lib.controller.checks import checkRegexp
from lib.controller.checks import checkConnection
from lib.controller.checks import checkNullConnection
from lib.controller.checks import checkWaf
from lib.controller.checks import heuristicCheckSqlInjection
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import extractRegexResult from lib.core.common import extractRegexResult, getFilteredPageContent, getPublicTypeMembers, getUnicode,\
from lib.core.common import getFilteredPageContent hashDBRetrieve, hashDBWrite, intersect, parseTargetUrl, randomStr, readInput, showHttpErrorCodes, urlencode, \
from lib.core.common import getPublicTypeMembers urldecode
from lib.core.common import getUnicode
from lib.core.common import hashDBRetrieve from lib.core.data import conf, kb, logger
from lib.core.common import hashDBWrite from lib.core.enums import HASHDB_KEYS, HEURISTIC_TEST, HTTPMETHOD, PAYLOAD, PLACE
from lib.core.common import intersect from lib.core.exception import exceptionsTuple, sqlmapNoneDataException, sqlmapNotVulnerableException,\
from lib.core.common import parseTargetUrl sqlmapSilentQuitException, sqlmapValueException, sqlmapUserQuitException
from lib.core.common import randomStr from lib.core.settings import ASP_NET_CONTROL_REGEX, DEFAULT_GET_POST_DELIMITER, EMPTY_FORM_FIELDS_REGEX,\
from lib.core.common import readInput IGNORE_PARAMETERS, LOW_TEXT_PERCENT, HOST_ALIASES, REFERER_ALIASES, USER_AGENT_ALIASES
from lib.core.common import showHttpErrorCodes from lib.core.target import initTargetEnv, setupTargetEnv
from lib.core.common import urlencode
from lib.core.common import urldecode
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.enums import HASHDB_KEYS
from lib.core.enums import HEURISTIC_TEST
from lib.core.enums import HTTPHEADER
from lib.core.enums import HTTPMETHOD
from lib.core.enums import PAYLOAD
from lib.core.enums import PLACE
from lib.core.exception import exceptionsTuple
from lib.core.exception import sqlmapNoneDataException
from lib.core.exception import sqlmapNotVulnerableException
from lib.core.exception import sqlmapSilentQuitException
from lib.core.exception import sqlmapValueException
from lib.core.exception import sqlmapUserQuitException
from lib.core.settings import ASP_NET_CONTROL_REGEX
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
from lib.core.settings import EMPTY_FORM_FIELDS_REGEX
from lib.core.settings import IGNORE_PARAMETERS
from lib.core.settings import LOW_TEXT_PERCENT
from lib.core.settings import HOST_ALIASES
from lib.core.settings import REFERER_ALIASES
from lib.core.settings import USER_AGENT_ALIASES
from lib.core.target import initTargetEnv
from lib.core.target import setupTargetEnv
from thirdparty.pagerank.pagerank import get_pagerank from thirdparty.pagerank.pagerank import get_pagerank
def __selectInjection(): def __selectInjection():

View File

@ -6,18 +6,9 @@ See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.data import conf from lib.core.data import conf, logger
from lib.core.data import logger from lib.core.settings import MSSQL_ALIASES, MYSQL_ALIASES, ORACLE_ALIASES, PGSQL_ALIASES, SQLITE_ALIASES,\
from lib.core.settings import MSSQL_ALIASES ACCESS_ALIASES, FIREBIRD_ALIASES, MAXDB_ALIASES, SYBASE_ALIASES, DB2_ALIASES
from lib.core.settings import MYSQL_ALIASES
from lib.core.settings import ORACLE_ALIASES
from lib.core.settings import PGSQL_ALIASES
from lib.core.settings import SQLITE_ALIASES
from lib.core.settings import ACCESS_ALIASES
from lib.core.settings import FIREBIRD_ALIASES
from lib.core.settings import MAXDB_ALIASES
from lib.core.settings import SYBASE_ALIASES
from lib.core.settings import DB2_ALIASES
from plugins.dbms.mssqlserver import MSSQLServerMap from plugins.dbms.mssqlserver import MSSQLServerMap
from plugins.dbms.mssqlserver.connector import Connector as MSSQLServerConn from plugins.dbms.mssqlserver.connector import Connector as MSSQLServerConn

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -7,31 +7,13 @@ See the file 'doc/COPYING' for copying permission
import re import re
from xml.etree import ElementTree as ET from lib.core.common import Backend, extractRegexResult, getSQLSnippet, isDBMSVersionAtLeast, isNumber, \
isTechniqueAvailable, randomInt, randomStr, singleTimeWarnMessage
from lib.core.common import Backend from lib.core.data import conf, kb, queries
from lib.core.common import extractRegexResult
from lib.core.common import getSQLSnippet
from lib.core.common import isDBMSVersionAtLeast
from lib.core.common import isNumber
from lib.core.common import isTechniqueAvailable
from lib.core.common import randomInt
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 queries
from lib.core.dicts import FROM_DUMMY_TABLE from lib.core.dicts import FROM_DUMMY_TABLE
from lib.core.dicts import SQL_STATEMENTS from lib.core.enums import DBMS, PAYLOAD, PLACE, POST_HINT
from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD
from lib.core.enums import PLACE
from lib.core.enums import POST_HINT
from lib.core.exception import sqlmapNoneDataException from lib.core.exception import sqlmapNoneDataException
from lib.core.settings import ASTERISK_MARKER from lib.core.settings import ASTERISK_MARKER, CUSTOM_INJECTION_MARK_CHAR, GENERIC_SQL_COMMENT ,PAYLOAD_DELIMITER
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
from lib.core.settings import GENERIC_SQL_COMMENT
from lib.core.settings import PAYLOAD_DELIMITER
from lib.core.unescaper import unescaper from lib.core.unescaper import unescaper
class Agent: class Agent:

View File

@ -15,7 +15,6 @@ import inspect
import logging import logging
import ntpath import ntpath
import os import os
import pickle
import posixpath import posixpath
import random import random
import re import re
@ -27,113 +26,50 @@ import time
import urllib import urllib
import urlparse import urlparse
import unicodedata import unicodedata
from ConfigParser import DEFAULTSECT, RawConfigParser
from ConfigParser import DEFAULTSECT
from ConfigParser import RawConfigParser
from StringIO import StringIO
from difflib import SequenceMatcher from difflib import SequenceMatcher
from math import sqrt from math import sqrt
from optparse import OptionValueError from optparse import OptionValueError
from subprocess import PIPE from subprocess import PIPE
from subprocess import Popen as execute from subprocess import Popen as execute
from tempfile import mkstemp
from xml.etree import ElementTree as ET
from xml.dom import minidom from xml.dom import minidom
from xml.sax import parse from xml.sax import parse
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from extra.cloak.cloak import decloak from extra.cloak.cloak import decloak
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.bigarray import BigArray from lib.core.bigarray import BigArray
from lib.core.data import conf from lib.core.data import conf, kb, logger, paths
from lib.core.data import kb from lib.core.convert import base64pickle, base64unpickle, htmlunescape, stdoutencode, unicodeencode, utf8encode
from lib.core.data import logger
from lib.core.data import paths
from lib.core.convert import base64pickle
from lib.core.convert import base64unpickle
from lib.core.convert import htmlunescape
from lib.core.convert import stdoutencode
from lib.core.convert import unicodeencode
from lib.core.convert import utf8encode
from lib.core.decorators import cachedmethod from lib.core.decorators import cachedmethod
from lib.core.dicts import DBMS_DICT from lib.core.dicts import DBMS_DICT
from lib.core.dicts import DEPRECATED_HINTS from lib.core.dicts import DEPRECATED_HINTS
from lib.core.dicts import SQL_STATEMENTS from lib.core.dicts import SQL_STATEMENTS
from lib.core.enums import ADJUST_TIME_DELAY from lib.core.enums import ADJUST_TIME_DELAY, CHARSET_TYPE, DBMS, EXPECTED, HEURISTIC_TEST, HTTPHEADER, HTTPMETHOD, \
from lib.core.enums import CHARSET_TYPE OS, PLACE, PAYLOAD, REFLECTIVE_COUNTER, SORT_ORDER
from lib.core.enums import DBMS from lib.core.exception import sqlmapDataException, sqlmapFilePathException, sqlmapGenericException, \
from lib.core.enums import EXPECTED sqlmapNoneDataException, sqlmapMissingDependence, sqlmapSilentQuitException, sqlmapSyntaxException, \
from lib.core.enums import HEURISTIC_TEST sqlmapUserQuitException
from lib.core.enums import HTTPHEADER
from lib.core.enums import HTTPMETHOD
from lib.core.enums import OS
from lib.core.enums import PLACE
from lib.core.enums import PAYLOAD
from lib.core.enums import REFLECTIVE_COUNTER
from lib.core.enums import SORT_ORDER
from lib.core.exception import sqlmapDataException
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapNoneDataException
from lib.core.exception import sqlmapMissingDependence
from lib.core.exception import sqlmapSilentQuitException
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapUserQuitException
from lib.core.log import FORMATTER
from lib.core.log import LOGGER_HANDLER from lib.core.log import LOGGER_HANDLER
from lib.core.optiondict import optDict from lib.core.optiondict import optDict
from lib.core.settings import BOLD_PATTERNS from lib.core.settings import BOLD_PATTERNS, CUSTOM_INJECTION_MARK_CHAR, DBMS_DIRECTORY_DICT,\
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR DEFAULT_COOKIE_DELIMITER,DEFAULT_GET_POST_DELIMITER, DEFAULT_MSSQL_SCHEMA, DEPRECATED_OPTIONS, DESCRIPTION, \
from lib.core.settings import DBMS_DIRECTORY_DICT DUMMY_SQL_INJECTION_CHARS, DUMMY_USER_INJECTION, DYNAMICITY_MARK_LENGTH, ERROR_PARSING_REGEXES, \
from lib.core.settings import DEFAULT_COOKIE_DELIMITER FORM_SEARCH_REGEX, GENERIC_DOC_ROOT_DIRECTORY_NAMES, HASHDB_MILESTONE_VALUE, HOST_ALIASES,\
from lib.core.settings import DEFAULT_GET_POST_DELIMITER INFERENCE_UNKNOWN_CHAR, ISSUES_PAGE, IS_WIN, LARGE_OUTPUT_THRESHOLD, MIN_TIME_RESPONSES, ML, \
from lib.core.settings import DEFAULT_MSSQL_SCHEMA NULL, PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER, PARTIAL_VALUE_MARKER, PAYLOAD_DELIMITER,\
from lib.core.settings import DEPRECATED_OPTIONS PLATFORM, PRINTABLE_CHAR_REGEX, PYVERSION, REFERER_ALIASES, REFLECTED_BORDER_REGEX, REFLECTED_MAX_REGEX_PARTS, \
from lib.core.settings import DESCRIPTION REFLECTED_REPLACEMENT_REGEX, REFLECTED_VALUE_MARKER, REFLECTIVE_MISS_THRESHOLD, REVISION, SENSITIVE_DATA_REGEX, \
from lib.core.settings import DUMMY_SQL_INJECTION_CHARS SITE, SUPPORTED_DBMS, TEXT_TAG_REGEX, TIME_STDEV_COEFF, UNICODE_ENCODING, UNKNOWN_DBMS_VERSION, \
from lib.core.settings import DUMMY_USER_INJECTION URI_QUESTION_MARKER, URLENCODE_CHAR_LIMIT, URLENCODE_FAILSAFE_CHARS, USER_AGENT_ALIASES, VERSION, VERSION_STRING
from lib.core.settings import DYNAMICITY_MARK_LENGTH
from lib.core.settings import ERROR_PARSING_REGEXES
from lib.core.settings import FORM_SEARCH_REGEX
from lib.core.settings import GENERIC_DOC_ROOT_DIRECTORY_NAMES
from lib.core.settings import HASHDB_MILESTONE_VALUE
from lib.core.settings import HOST_ALIASES
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
from lib.core.settings import ISSUES_PAGE
from lib.core.settings import IS_WIN
from lib.core.settings import LARGE_OUTPUT_THRESHOLD
from lib.core.settings import MIN_TIME_RESPONSES
from lib.core.settings import ML
from lib.core.settings import NULL
from lib.core.settings import PARAMETER_AMP_MARKER
from lib.core.settings import PARAMETER_SEMICOLON_MARKER
from lib.core.settings import PARTIAL_VALUE_MARKER
from lib.core.settings import PAYLOAD_DELIMITER
from lib.core.settings import PLATFORM
from lib.core.settings import PRINTABLE_CHAR_REGEX
from lib.core.settings import PYVERSION
from lib.core.settings import REFERER_ALIASES
from lib.core.settings import REFLECTED_BORDER_REGEX
from lib.core.settings import REFLECTED_MAX_REGEX_PARTS
from lib.core.settings import REFLECTED_REPLACEMENT_REGEX
from lib.core.settings import REFLECTED_VALUE_MARKER
from lib.core.settings import REFLECTIVE_MISS_THRESHOLD
from lib.core.settings import REVISION
from lib.core.settings import SENSITIVE_DATA_REGEX
from lib.core.settings import SITE
from lib.core.settings import SUPPORTED_DBMS
from lib.core.settings import TEXT_TAG_REGEX
from lib.core.settings import TIME_STDEV_COEFF
from lib.core.settings import UNICODE_ENCODING
from lib.core.settings import UNKNOWN_DBMS_VERSION
from lib.core.settings import URI_QUESTION_MARKER
from lib.core.settings import URLENCODE_CHAR_LIMIT
from lib.core.settings import URLENCODE_FAILSAFE_CHARS
from lib.core.settings import USER_AGENT_ALIASES
from lib.core.settings import VERSION
from lib.core.settings import VERSION_STRING
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
from thirdparty.clientform.clientform import ParseResponse from thirdparty.clientform.clientform import ParseResponse, ParseError
from thirdparty.clientform.clientform import ParseError
from thirdparty.magic import magic from thirdparty.magic import magic
from thirdparty.odict.odict import OrderedDict from thirdparty.odict.odict import OrderedDict
from thirdparty.termcolor.termcolor import colored from thirdparty.termcolor.termcolor import colored

View File

@ -7,17 +7,14 @@ See the file 'doc/COPYING' for copying permission
try: try:
import hashlib import hashlib
except: except ImportError:
import md5 import md5
import sha import sha
import pickle import pickle
import re
import sys import sys
import struct import struct
import urllib
from lib.core.enums import PLACE
from lib.core.settings import IS_WIN from lib.core.settings import IS_WIN
from lib.core.settings import UNICODE_ENCODING from lib.core.settings import UNICODE_ENCODING
@ -31,9 +28,8 @@ def base64pickle(value):
retVal = None retVal = None
try: try:
retVal = base64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) retVal = base64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
except: except pickle.PicklingError:
warnMsg = "problem occurred while serializing " warnMsg = "problem occurred while serializing instance of a type '%s'" % type(value)
warnMsg += "instance of a type '%s'" % type(value)
singleTimeWarnMessage(warnMsg) singleTimeWarnMessage(warnMsg)
retVal = base64encode(pickle.dumps(str(value), pickle.HIGHEST_PROTOCOL)) retVal = base64encode(pickle.dumps(str(value), pickle.HIGHEST_PROTOCOL))
@ -116,7 +112,7 @@ def stdoutencode(data):
warnMsg = "cannot properly display Unicode characters " warnMsg = "cannot properly display Unicode characters "
warnMsg += "inside Windows OS command prompt " warnMsg += "inside Windows OS command prompt "
warnMsg += "(http://bugs.python.org/issue1602). All " warnMsg += "(http://bugs.python.org/issue1602). All "
warnMsg += "unhandled occurances will result in " warnMsg += "unhandled occurrences will result in "
warnMsg += "replacement with '?' character. Please, find " warnMsg += "replacement with '?' character. Please, find "
warnMsg += "proper character representation inside " warnMsg += "proper character representation inside "
warnMsg += "corresponding output files. " warnMsg += "corresponding output files. "

View File

@ -5,201 +5,190 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.enums import DBMS from lib.core.enums import DBMS, POST_HINT
from lib.core.enums import POST_HINT from lib.core.settings import BLANK, NULL, MSSQL_ALIASES, MYSQL_ALIASES, PGSQL_ALIASES, ORACLE_ALIASES,\
from lib.core.settings import BLANK SQLITE_ALIASES, ACCESS_ALIASES, FIREBIRD_ALIASES, MAXDB_ALIASES, SYBASE_ALIASES, DB2_ALIASES
from lib.core.settings import NULL
from lib.core.settings import MSSQL_ALIASES
from lib.core.settings import MYSQL_ALIASES
from lib.core.settings import PGSQL_ALIASES
from lib.core.settings import ORACLE_ALIASES
from lib.core.settings import SQLITE_ALIASES
from lib.core.settings import ACCESS_ALIASES
from lib.core.settings import FIREBIRD_ALIASES
from lib.core.settings import MAXDB_ALIASES
from lib.core.settings import SYBASE_ALIASES
from lib.core.settings import DB2_ALIASES
FIREBIRD_TYPES = { FIREBIRD_TYPES = {
"261":"BLOB", "261": "BLOB",
"14":"CHAR", "14": "CHAR",
"40":"CSTRING", "40": "CSTRING",
"11":"D_FLOAT", "11": "D_FLOAT",
"27":"DOUBLE", "27": "DOUBLE",
"10":"FLOAT", "10": "FLOAT",
"16":"INT64", "16": "INT64",
"8":"INTEGER", "8": "INTEGER",
"9":"QUAD", "9": "QUAD",
"7":"SMALLINT", "7": "SMALLINT",
"12":"DATE", "12": "DATE",
"13":"TIME", "13": "TIME",
"35":"TIMESTAMP", "35": "TIMESTAMP",
"37":"VARCHAR" "37": "VARCHAR"
} }
SYBASE_TYPES = { SYBASE_TYPES = {
"14":"floatn", "14": "floatn",
"8":"float", "8": "float",
"15":"datetimn", "15": "datetimn",
"12":"datetime", "12": "datetime",
"23":"real", "23": "real",
"28":"numericn", "28": "numericn",
"10":"numeric", "10": "numeric",
"27":"decimaln", "27": "decimaln",
"26":"decimal", "26": "decimal",
"17":"moneyn", "17": "moneyn",
"11":"money", "11": "money",
"21":"smallmoney", "21": "smallmoney",
"22":"smalldatetime", "22": "smalldatetime",
"13":"intn", "13": "intn",
"7":"int", "7": "int",
"6":"smallint", "6": "smallint",
"5":"tinyint", "5": "tinyint",
"16":"bit", "16": "bit",
"2":"varchar", "2": "varchar",
"18":"sysname", "18": "sysname",
"25":"nvarchar", "25": "nvarchar",
"1":"char", "1": "char",
"24":"nchar", "24": "nchar",
"4":"varbinary", "4": "varbinary",
"80":"timestamp", "80": "timestamp",
"3":"binary", "3": "binary",
"19":"text", "19": "text",
"20":"image", "20": "image",
} }
MYSQL_PRIVS = { MYSQL_PRIVS = {
1:"select_priv", 1: "select_priv",
2:"insert_priv", 2: "insert_priv",
3:"update_priv", 3: "update_priv",
4:"delete_priv", 4: "delete_priv",
5:"create_priv", 5: "create_priv",
6:"drop_priv", 6: "drop_priv",
7:"reload_priv", 7: "reload_priv",
8:"shutdown_priv", 8: "shutdown_priv",
9:"process_priv", 9: "process_priv",
10:"file_priv", 10: "file_priv",
11:"grant_priv", 11: "grant_priv",
12:"references_priv", 12: "references_priv",
13:"index_priv", 13: "index_priv",
14:"alter_priv", 14: "alter_priv",
15:"show_db_priv", 15: "show_db_priv",
16:"super_priv", 16: "super_priv",
17:"create_tmp_table_priv", 17: "create_tmp_table_priv",
18:"lock_tables_priv", 18: "lock_tables_priv",
19:"execute_priv", 19: "execute_priv",
20:"repl_slave_priv", 20: "repl_slave_priv",
21:"repl_client_priv", 21: "repl_client_priv",
22:"create_view_priv", 22: "create_view_priv",
23:"show_view_priv", 23: "show_view_priv",
24:"create_routine_priv", 24: "create_routine_priv",
25:"alter_routine_priv", 25: "alter_routine_priv",
26:"create_user_priv", 26: "create_user_priv",
} }
PGSQL_PRIVS = { PGSQL_PRIVS = {
1:"createdb", 1: "createdb",
2:"super", 2: "super",
3:"catupd", 3: "catupd",
} }
FIREBIRD_PRIVS = { FIREBIRD_PRIVS = {
"S": "SELECT", "S": "SELECT",
"I": "INSERT", "I": "INSERT",
"U": "UPDATE", "U": "UPDATE",
"D": "DELETE", "D": "DELETE",
"R": "REFERENCES", "R": "REFERENCES",
"E": "EXECUTE" "E": "EXECUTE"
} }
DB2_PRIVS = { DB2_PRIVS = {
1: "CONTROLAUTH", 1: "CONTROLAUTH",
2: "ALTERAUTH", 2: "ALTERAUTH",
3: "DELETEAUTH", 3: "DELETEAUTH",
4: "INDEXAUTH", 4: "INDEXAUTH",
5: "INSERTAUTH", 5: "INSERTAUTH",
6: "REFAUTH", 6: "REFAUTH",
7: "SELECTAUTH", 7: "SELECTAUTH",
8: "UPDATEAUTH" 8: "UPDATEAUTH"
} }
DUMP_REPLACEMENTS = {" ": NULL, "": BLANK} DUMP_REPLACEMENTS = {" ": NULL, "": BLANK}
DBMS_DICT = { DBMS_DICT = {
DBMS.MSSQL: (MSSQL_ALIASES, "python-pymssql", "http://pymssql.sourceforge.net/"), DBMS.MSSQL: (MSSQL_ALIASES, "python-pymssql", "http://pymssql.sourceforge.net/"),
DBMS.MYSQL: (MYSQL_ALIASES, "python pymysql", "http://code.google.com/p/pymysql/"), DBMS.MYSQL: (MYSQL_ALIASES, "python pymysql", "http://code.google.com/p/pymysql/"),
DBMS.PGSQL: (PGSQL_ALIASES, "python-psycopg2", "http://initd.org/psycopg/"), DBMS.PGSQL: (PGSQL_ALIASES, "python-psycopg2", "http://initd.org/psycopg/"),
DBMS.ORACLE: (ORACLE_ALIASES, "python cx_Oracle", "http://cx-oracle.sourceforge.net/"), DBMS.ORACLE: (ORACLE_ALIASES, "python cx_Oracle", "http://cx-oracle.sourceforge.net/"),
DBMS.SQLITE: (SQLITE_ALIASES, "python-pysqlite2", "http://pysqlite.googlecode.com/"), DBMS.SQLITE: (SQLITE_ALIASES, "python-pysqlite2", "http://pysqlite.googlecode.com/"),
DBMS.ACCESS: (ACCESS_ALIASES, "python-pyodbc", "http://pyodbc.googlecode.com/"), DBMS.ACCESS: (ACCESS_ALIASES, "python-pyodbc", "http://pyodbc.googlecode.com/"),
DBMS.FIREBIRD: (FIREBIRD_ALIASES, "python-kinterbasdb", "http://kinterbasdb.sourceforge.net/"), DBMS.FIREBIRD: (FIREBIRD_ALIASES, "python-kinterbasdb", "http://kinterbasdb.sourceforge.net/"),
DBMS.MAXDB: (MAXDB_ALIASES, None, None), DBMS.MAXDB: (MAXDB_ALIASES, None, None),
DBMS.SYBASE: (SYBASE_ALIASES, "python-pymssql", "http://pymssql.sourceforge.net/"), DBMS.SYBASE: (SYBASE_ALIASES, "python-pymssql", "http://pymssql.sourceforge.net/"),
DBMS.DB2: (DB2_ALIASES, "python ibm-db", "http://code.google.com/p/ibm-db/") DBMS.DB2: (DB2_ALIASES, "python ibm-db", "http://code.google.com/p/ibm-db/")
} }
FROM_DUMMY_TABLE = { FROM_DUMMY_TABLE = {
DBMS.ORACLE: " FROM DUAL", DBMS.ORACLE: " FROM DUAL",
DBMS.ACCESS: " FROM MSysAccessObjects", DBMS.ACCESS: " FROM MSysAccessObjects",
DBMS.FIREBIRD: " FROM RDB$DATABASE", DBMS.FIREBIRD: " FROM RDB$DATABASE",
DBMS.MAXDB: " FROM VERSIONS", DBMS.MAXDB: " FROM VERSIONS",
DBMS.DB2: " FROM SYSIBM.SYSDUMMY1" DBMS.DB2: " FROM SYSIBM.SYSDUMMY1"
} }
SQL_STATEMENTS = { SQL_STATEMENTS = {
"SQL SELECT statement": ( "SQL SELECT statement": (
"select ", "select ",
"show ", "show ",
" top ", " top ",
" distinct ", " distinct ",
" from ", " from ",
" from dual", " from dual",
" where ", " where ",
" group by ", " group by ",
" order by ", " order by ",
" having ", " having ",
" limit ", " limit ",
" offset ", " offset ",
" union all ", " union all ",
" rownum as ", " rownum as ",
"(case ", ), "(case ", ),
"SQL data definition": ( "SQL data definition": (
"create ", "create ",
"declare ", "declare ",
"drop ", "drop ",
"truncate ", "truncate ",
"alter ", ), "alter ", ),
"SQL data manipulation": ( "SQL data manipulation": (
"bulk ", "bulk ",
"insert ", "insert ",
"update ", "update ",
"delete ", "delete ",
"merge ", "merge ",
"load ", ), "load ", ),
"SQL data control": ( "SQL data control": (
"grant ", "grant ",
"revoke ", ), "revoke ", ),
"SQL data execution": ( "SQL data execution": (
"exec ", "exec ",
"execute ", ), "execute ", ),
"SQL transaction": ( "SQL transaction": (
"start transaction ", "start transaction ",
"begin work ", "begin work ",
"begin transaction ", "begin transaction ",
"commit ", "commit ",
"rollback ", ), "rollback ", ),
} }
POST_HINT_CONTENT_TYPES = { POST_HINT_CONTENT_TYPES = {
POST_HINT.JSON: "application/json", POST_HINT.JSON: "application/json",
POST_HINT.MULTIPART: "multipart/form-data", POST_HINT.MULTIPART: "multipart/form-data",
POST_HINT.SOAP: "application/soap+xml", POST_HINT.SOAP: "application/soap+xml",
POST_HINT.XML: "application/xml" POST_HINT.XML: "application/xml"
} }
DEPRECATED_HINTS = {"--replicate": "use '--dump-format=SQLITE' instead"} DEPRECATED_HINTS = {"--replicate": "use '--dump-format=SQLITE' instead"}

View File

@ -6,36 +6,19 @@ See the file 'doc/COPYING' for copying permission
""" """
import codecs import codecs
import re
import os import os
import StringIO
import threading import threading
from xml.dom.minidom import getDOMImplementation from xml.dom.minidom import getDOMImplementation
from lib.core.common import Backend from lib.core.common import Backend, dataToDumpFile, dataToStdout, getUnicode, isListLike, normalizeUnicode, \
from lib.core.common import dataToDumpFile openFile, prioritySortColumns, safeCSValue, unsafeSQLIdentificatorNaming
from lib.core.common import dataToStdout from lib.core.data import conf, kb, logger
from lib.core.common import getUnicode from lib.core.dicts import DUMP_REPLACEMENTS, DBMS
from lib.core.common import isListLike
from lib.core.common import normalizeUnicode
from lib.core.common import openFile
from lib.core.common import prioritySortColumns
from lib.core.common import safeCSValue
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.dicts import DUMP_REPLACEMENTS
from lib.core.enums import DBMS
from lib.core.enums import DUMP_FORMAT from lib.core.enums import DUMP_FORMAT
from lib.core.exception import sqlmapGenericException from lib.core.exception import sqlmapGenericException, sqlmapValueException
from lib.core.exception import sqlmapValueException
from lib.core.replication import Replication from lib.core.replication import Replication
from lib.core.settings import HTML_DUMP_CSS_STYLE from lib.core.settings import HTML_DUMP_CSS_STYLE, METADB_SUFFIX, TRIM_STDOUT_DUMP_SIZE, UNICODE_ENCODING
from lib.core.settings import METADB_SUFFIX
from lib.core.settings import TRIM_STDOUT_DUMP_SIZE
from lib.core.settings import UNICODE_ENCODING
class Dump: class Dump:
""" """

View File

@ -5,6 +5,8 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
#TODO: Moved all of these to namedtuple
class PRIORITY: class PRIORITY:
LOWEST = -100 LOWEST = -100
LOWER = -50 LOWER = -50
@ -14,6 +16,7 @@ class PRIORITY:
HIGHER = 50 HIGHER = 50
HIGHEST = 100 HIGHEST = 100
class SORT_ORDER: class SORT_ORDER:
FIRST = 0 FIRST = 0
SECOND = 1 SECOND = 1
@ -22,9 +25,10 @@ class SORT_ORDER:
FIFTH = 4 FIFTH = 4
LAST = 100 LAST = 100
class DBMS: class DBMS:
ACCESS = "Microsoft Access" ACCESS = "Microsoft Access"
DB2 = "IBM DB2" DB2 = "IBM DB2"
FIREBIRD = "Firebird" FIREBIRD = "Firebird"
MAXDB = "SAP MaxDB" MAXDB = "SAP MaxDB"
MSSQL = "Microsoft SQL Server" MSSQL = "Microsoft SQL Server"
@ -34,6 +38,7 @@ class DBMS:
SQLITE = "SQLite" SQLITE = "SQLite"
SYBASE = "Sybase" SYBASE = "Sybase"
class DBMS_DIRECTORY_NAME: class DBMS_DIRECTORY_NAME:
ACCESS = "access" ACCESS = "access"
DB2 = "db2" DB2 = "db2"
@ -46,15 +51,18 @@ class DBMS_DIRECTORY_NAME:
SQLITE = "sqlite" SQLITE = "sqlite"
SYBASE = "sybase" SYBASE = "sybase"
class CUSTOM_LOGGING: class CUSTOM_LOGGING:
PAYLOAD = 9 PAYLOAD = 9
TRAFFIC_OUT = 8 TRAFFIC_OUT = 8
TRAFFIC_IN = 7 TRAFFIC_IN = 7
class OS: class OS:
LINUX = "Linux" LINUX = "Linux"
WINDOWS = "Windows" WINDOWS = "Windows"
class PLACE: class PLACE:
GET = "GET" GET = "GET"
POST = "POST" POST = "POST"
@ -65,25 +73,30 @@ class PLACE:
HOST = "Host" HOST = "Host"
CUSTOM_POST = "(custom) POST" CUSTOM_POST = "(custom) POST"
class POST_HINT: class POST_HINT:
SOAP = "SOAP" SOAP = "SOAP"
JSON = "JSON" JSON = "JSON"
MULTIPART = "MULTIPART" MULTIPART = "MULTIPART"
XML = "XML (generic)" XML = "XML (generic)"
class HTTPMETHOD: class HTTPMETHOD:
GET = "GET" GET = "GET"
POST = "POST" POST = "POST"
HEAD = "HEAD" HEAD = "HEAD"
class NULLCONNECTION: class NULLCONNECTION:
HEAD = "HEAD" HEAD = "HEAD"
RANGE = "Range" RANGE = "Range"
class REFLECTIVE_COUNTER: class REFLECTIVE_COUNTER:
MISS = "MISS" MISS = "MISS"
HIT = "HIT" HIT = "HIT"
class CHARSET_TYPE: class CHARSET_TYPE:
BINARY = 1 BINARY = 1
DIGITS = 2 DIGITS = 2
@ -91,11 +104,13 @@ class CHARSET_TYPE:
ALPHA = 4 ALPHA = 4
ALPHANUM = 5 ALPHANUM = 5
class HEURISTIC_TEST: class HEURISTIC_TEST:
CASTED = 1 CASTED = 1
NEGATIVE = 2 NEGATIVE = 2
POSITIVE = 3 POSITIVE = 3
class HASH: class HASH:
MYSQL = r'(?i)\A\*[0-9a-f]{40}\Z' MYSQL = r'(?i)\A\*[0-9a-f]{40}\Z'
MYSQL_OLD = r'(?i)\A(?![0-9]+\Z)[0-9a-f]{16}\Z' MYSQL_OLD = r'(?i)\A(?![0-9]+\Z)[0-9a-f]{16}\Z'
@ -111,24 +126,33 @@ class HASH:
# Reference: http://www.zytrax.com/tech/web/mobile_ids.html # Reference: http://www.zytrax.com/tech/web/mobile_ids.html
class MOBILES: class MOBILES:
BLACKBERRY = ("BlackBerry 9900", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+") BLACKBERRY = ("BlackBerry 9900",
GALAXY = ("Samsung Galaxy S", "Mozilla/5.0 (Linux; U; Android 2.2; en-US; SGH-T959D Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1") "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+")
GALAXY = ("Samsung Galaxy S",
"Mozilla/5.0 (Linux; U; Android 2.2; en-US; SGH-T959D Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
HP = ("HP iPAQ 6365", "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6300)") HP = ("HP iPAQ 6365", "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6300)")
HTC = ("HTC Sensation", "Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30") HTC = ("HTC Sensation",
IPHONE = ("Apple iPhone 4s", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3") "Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
NEXUS = ("Google Nexus 7", "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19") IPHONE = ("Apple iPhone 4s",
NOKIA = ("Nokia N97", "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/10.0.012; Profile/MIDP-2.1 Configuration/CLDC-1.1; en-us) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.12344") "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3")
NEXUS = ("Google Nexus 7",
"Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19")
NOKIA = ("Nokia N97",
"Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/10.0.012; Profile/MIDP-2.1 Configuration/CLDC-1.1; en-us) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.12344")
class PROXY_TYPE: class PROXY_TYPE:
HTTP = "HTTP" HTTP = "HTTP"
SOCKS4 = "SOCKS4" SOCKS4 = "SOCKS4"
SOCKS5 = "SOCKS5" SOCKS5 = "SOCKS5"
class DUMP_FORMAT: class DUMP_FORMAT:
CSV = "CSV" CSV = "CSV"
HTML = "HTML" HTML = "HTML"
SQLITE = "SQLITE" SQLITE = "SQLITE"
class HTTPHEADER: class HTTPHEADER:
ACCEPT = "Accept" ACCEPT = "Accept"
ACCEPT_CHARSET = "Accept-Charset" ACCEPT_CHARSET = "Accept-Charset"
@ -151,10 +175,12 @@ class HTTPHEADER:
REFERER = "Referer" REFERER = "Referer"
USER_AGENT = "User-Agent" USER_AGENT = "User-Agent"
class EXPECTED: class EXPECTED:
BOOL = "bool" BOOL = "bool"
INT = "int" INT = "int"
class HASHDB_KEYS: class HASHDB_KEYS:
DBMS = "DBMS" DBMS = "DBMS"
CONF_TMP_PATH = "CONF_TMP_PATH" CONF_TMP_PATH = "CONF_TMP_PATH"
@ -167,46 +193,48 @@ class HASHDB_KEYS:
KB_XP_CMDSHELL_AVAILABLE = "KB_XP_CMDSHELL_AVAILABLE" KB_XP_CMDSHELL_AVAILABLE = "KB_XP_CMDSHELL_AVAILABLE"
OS = "OS" OS = "OS"
class REDIRECTION: class REDIRECTION:
YES = "Y" YES = "Y"
NO = "N" NO = "N"
class PAYLOAD: class PAYLOAD:
SQLINJECTION = { SQLINJECTION = {
1: "boolean-based blind", 1: "boolean-based blind",
2: "error-based", 2: "error-based",
3: "UNION query", 3: "UNION query",
4: "stacked queries", 4: "stacked queries",
5: "AND/OR time-based blind", 5: "AND/OR time-based blind",
6: "inline query" 6: "inline query"
} }
PARAMETER = { PARAMETER = {
1: "Unescaped numeric", 1: "Unescaped numeric",
2: "Single quoted string", 2: "Single quoted string",
3: "LIKE single quoted string", 3: "LIKE single quoted string",
4: "Double quoted string", 4: "Double quoted string",
5: "LIKE double quoted string" 5: "LIKE double quoted string"
} }
RISK = { RISK = {
0: "No risk", 0: "No risk",
1: "Low risk", 1: "Low risk",
2: "Medium risk", 2: "Medium risk",
3: "High risk" 3: "High risk"
} }
CLAUSE = { CLAUSE = {
0: "Always", 0: "Always",
1: "WHERE", 1: "WHERE",
2: "GROUP BY", 2: "GROUP BY",
3: "ORDER BY", 3: "ORDER BY",
4: "LIMIT", 4: "LIMIT",
5: "OFFSET", 5: "OFFSET",
6: "TOP", 6: "TOP",
7: "Table name", 7: "Table name",
8: "Column name" 8: "Column name"
} }
class METHOD: class METHOD:
COMPARISON = "comparison" COMPARISON = "comparison"
@ -227,16 +255,21 @@ class PAYLOAD:
NEGATIVE = 2 NEGATIVE = 2
REPLACE = 3 REPLACE = 3
class WIZARD: class WIZARD:
BASIC = ("getBanner", "getCurrentUser", "getCurrentDb", "isDba") BASIC = ("getBanner", "getCurrentUser", "getCurrentDb", "isDba")
SMART = ("getBanner", "getCurrentUser", "getCurrentDb", "isDba", "getUsers", "getDbs", "getTables", "getSchema", "excludeSysDbs") SMART = ("getBanner", "getCurrentUser", "getCurrentDb", "isDba", "getUsers", "getDbs", "getTables", "getSchema",
ALL = ("getBanner", "getCurrentUser", "getCurrentDb", "isDba", "getHostname", "getUsers", "getPasswordHashes", "getPrivileges", "getRoles", "dumpAll") "excludeSysDbs")
ALL = ("getBanner", "getCurrentUser", "getCurrentDb", "isDba", "getHostname", "getUsers", "getPasswordHashes",
"getPrivileges", "getRoles", "dumpAll")
class ADJUST_TIME_DELAY: class ADJUST_TIME_DELAY:
DISABLE = -1 DISABLE = -1
NO = 0 NO = 0
YES = 1 YES = 1
class WEB_API: class WEB_API:
PHP = "php" PHP = "php"
ASP = "asp" ASP = "asp"

View File

@ -8,76 +8,94 @@ See the file 'doc/COPYING' for copying permission
class sqlmapCompressionException(Exception): class sqlmapCompressionException(Exception):
pass pass
class sqlmapConnectionException(Exception): class sqlmapConnectionException(Exception):
pass pass
class sqlmapDataException(Exception): class sqlmapDataException(Exception):
pass pass
class sqlmapFilePathException(Exception): class sqlmapFilePathException(Exception):
pass pass
class sqlmapGenericException(Exception): class sqlmapGenericException(Exception):
pass pass
class sqlmapMissingDependence(Exception): class sqlmapMissingDependence(Exception):
pass pass
class sqlmapMissingMandatoryOptionException(Exception): class sqlmapMissingMandatoryOptionException(Exception):
pass pass
class sqlmapMissingPrivileges(Exception): class sqlmapMissingPrivileges(Exception):
pass pass
class sqlmapNoneDataException(Exception): class sqlmapNoneDataException(Exception):
pass pass
class sqlmapNotVulnerableException(Exception): class sqlmapNotVulnerableException(Exception):
pass pass
class sqlmapSilentQuitException(Exception): class sqlmapSilentQuitException(Exception):
pass pass
class sqlmapUserQuitException(Exception): class sqlmapUserQuitException(Exception):
pass pass
class sqlmapRegExprException(Exception): class sqlmapRegExprException(Exception):
pass pass
class sqlmapSyntaxException(Exception): class sqlmapSyntaxException(Exception):
pass pass
class sqlmapThreadException(Exception): class sqlmapThreadException(Exception):
pass pass
class sqlmapUndefinedMethod(Exception): class sqlmapUndefinedMethod(Exception):
pass pass
class sqlmapUnsupportedDBMSException(Exception): class sqlmapUnsupportedDBMSException(Exception):
pass pass
class sqlmapUnsupportedFeatureException(Exception): class sqlmapUnsupportedFeatureException(Exception):
pass pass
class sqlmapValueException(Exception): class sqlmapValueException(Exception):
pass pass
exceptionsTuple = ( exceptionsTuple = (
sqlmapCompressionException, sqlmapCompressionException,
sqlmapConnectionException, sqlmapConnectionException,
sqlmapDataException, sqlmapDataException,
sqlmapFilePathException, sqlmapFilePathException,
sqlmapGenericException, sqlmapGenericException,
sqlmapMissingDependence, sqlmapMissingDependence,
sqlmapMissingMandatoryOptionException, sqlmapMissingMandatoryOptionException,
sqlmapNoneDataException, sqlmapNoneDataException,
sqlmapRegExprException, sqlmapRegExprException,
sqlmapSyntaxException, sqlmapSyntaxException,
sqlmapUndefinedMethod, sqlmapUndefinedMethod,
sqlmapMissingPrivileges, sqlmapMissingPrivileges,
sqlmapNotVulnerableException, sqlmapNotVulnerableException,
sqlmapThreadException, sqlmapThreadException,
sqlmapUnsupportedDBMSException, sqlmapUnsupportedDBMSException,
sqlmapUnsupportedFeatureException, sqlmapUnsupportedFeatureException,
sqlmapValueException, sqlmapValueException,
) )

View File

@ -8,256 +8,256 @@ See the file 'doc/COPYING' for copying permission
# Reference: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/entities.html # Reference: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/entities.html
htmlEntities = { htmlEntities = {
'quot': 34, 'quot': 34,
'amp': 38, 'amp': 38,
'lt': 60, 'lt': 60,
'gt': 62, 'gt': 62,
'nbsp': 160, 'nbsp': 160,
'iexcl': 161, 'iexcl': 161,
'cent': 162, 'cent': 162,
'pound': 163, 'pound': 163,
'curren': 164, 'curren': 164,
'yen': 165, 'yen': 165,
'brvbar': 166, 'brvbar': 166,
'sect': 167, 'sect': 167,
'uml': 168, 'uml': 168,
'copy': 169, 'copy': 169,
'ordf': 170, 'ordf': 170,
'laquo': 171, 'laquo': 171,
'not': 172, 'not': 172,
'shy': 173, 'shy': 173,
'reg': 174, 'reg': 174,
'macr': 175, 'macr': 175,
'deg': 176, 'deg': 176,
'plusmn': 177, 'plusmn': 177,
'sup2': 178, 'sup2': 178,
'sup3': 179, 'sup3': 179,
'acute': 180, 'acute': 180,
'micro': 181, 'micro': 181,
'para': 182, 'para': 182,
'middot': 183, 'middot': 183,
'cedil': 184, 'cedil': 184,
'sup1': 185, 'sup1': 185,
'ordm': 186, 'ordm': 186,
'raquo': 187, 'raquo': 187,
'frac14': 188, 'frac14': 188,
'frac12': 189, 'frac12': 189,
'frac34': 190, 'frac34': 190,
'iquest': 191, 'iquest': 191,
'Agrave': 192, 'Agrave': 192,
'Aacute': 193, 'Aacute': 193,
'Acirc': 194, 'Acirc': 194,
'Atilde': 195, 'Atilde': 195,
'Auml': 196, 'Auml': 196,
'Aring': 197, 'Aring': 197,
'AElig': 198, 'AElig': 198,
'Ccedil': 199, 'Ccedil': 199,
'Egrave': 200, 'Egrave': 200,
'Eacute': 201, 'Eacute': 201,
'Ecirc': 202, 'Ecirc': 202,
'Euml': 203, 'Euml': 203,
'Igrave': 204, 'Igrave': 204,
'Iacute': 205, 'Iacute': 205,
'Icirc': 206, 'Icirc': 206,
'Iuml': 207, 'Iuml': 207,
'ETH': 208, 'ETH': 208,
'Ntilde': 209, 'Ntilde': 209,
'Ograve': 210, 'Ograve': 210,
'Oacute': 211, 'Oacute': 211,
'Ocirc': 212, 'Ocirc': 212,
'Otilde': 213, 'Otilde': 213,
'Ouml': 214, 'Ouml': 214,
'times': 215, 'times': 215,
'Oslash': 216, 'Oslash': 216,
'Ugrave': 217, 'Ugrave': 217,
'Uacute': 218, 'Uacute': 218,
'Ucirc': 219, 'Ucirc': 219,
'Uuml': 220, 'Uuml': 220,
'Yacute': 221, 'Yacute': 221,
'THORN': 222, 'THORN': 222,
'szlig': 223, 'szlig': 223,
'agrave': 224, 'agrave': 224,
'aacute': 225, 'aacute': 225,
'acirc': 226, 'acirc': 226,
'atilde': 227, 'atilde': 227,
'auml': 228, 'auml': 228,
'aring': 229, 'aring': 229,
'aelig': 230, 'aelig': 230,
'ccedil': 231, 'ccedil': 231,
'egrave': 232, 'egrave': 232,
'eacute': 233, 'eacute': 233,
'ecirc': 234, 'ecirc': 234,
'euml': 235, 'euml': 235,
'igrave': 236, 'igrave': 236,
'iacute': 237, 'iacute': 237,
'icirc': 238, 'icirc': 238,
'iuml': 239, 'iuml': 239,
'eth': 240, 'eth': 240,
'ntilde': 241, 'ntilde': 241,
'ograve': 242, 'ograve': 242,
'oacute': 243, 'oacute': 243,
'ocirc': 244, 'ocirc': 244,
'otilde': 245, 'otilde': 245,
'ouml': 246, 'ouml': 246,
'divide': 247, 'divide': 247,
'oslash': 248, 'oslash': 248,
'ugrave': 249, 'ugrave': 249,
'uacute': 250, 'uacute': 250,
'ucirc': 251, 'ucirc': 251,
'uuml': 252, 'uuml': 252,
'yacute': 253, 'yacute': 253,
'thorn': 254, 'thorn': 254,
'yuml': 255, 'yuml': 255,
'OElig': 338, 'OElig': 338,
'oelig': 339, 'oelig': 339,
'Scaron': 352, 'Scaron': 352,
'fnof': 402, 'fnof': 402,
'scaron': 353, 'scaron': 353,
'Yuml': 376, 'Yuml': 376,
'circ': 710, 'circ': 710,
'tilde': 732, 'tilde': 732,
'Alpha': 913, 'Alpha': 913,
'Beta': 914, 'Beta': 914,
'Gamma': 915, 'Gamma': 915,
'Delta': 916, 'Delta': 916,
'Epsilon': 917, 'Epsilon': 917,
'Zeta': 918, 'Zeta': 918,
'Eta': 919, 'Eta': 919,
'Theta': 920, 'Theta': 920,
'Iota': 921, 'Iota': 921,
'Kappa': 922, 'Kappa': 922,
'Lambda': 923, 'Lambda': 923,
'Mu': 924, 'Mu': 924,
'Nu': 925, 'Nu': 925,
'Xi': 926, 'Xi': 926,
'Omicron': 927, 'Omicron': 927,
'Pi': 928, 'Pi': 928,
'Rho': 929, 'Rho': 929,
'Sigma': 931, 'Sigma': 931,
'Tau': 932, 'Tau': 932,
'Upsilon': 933, 'Upsilon': 933,
'Phi': 934, 'Phi': 934,
'Chi': 935, 'Chi': 935,
'Psi': 936, 'Psi': 936,
'Omega': 937, 'Omega': 937,
'alpha': 945, 'alpha': 945,
'beta': 946, 'beta': 946,
'gamma': 947, 'gamma': 947,
'delta': 948, 'delta': 948,
'epsilon': 949, 'epsilon': 949,
'zeta': 950, 'zeta': 950,
'eta': 951, 'eta': 951,
'theta': 952, 'theta': 952,
'iota': 953, 'iota': 953,
'kappa': 954, 'kappa': 954,
'lambda': 955, 'lambda': 955,
'mu': 956, 'mu': 956,
'nu': 957, 'nu': 957,
'xi': 958, 'xi': 958,
'omicron': 959, 'omicron': 959,
'pi': 960, 'pi': 960,
'rho': 961, 'rho': 961,
'sigmaf': 962, 'sigmaf': 962,
'sigma': 963, 'sigma': 963,
'tau': 964, 'tau': 964,
'upsilon': 965, 'upsilon': 965,
'phi': 966, 'phi': 966,
'chi': 967, 'chi': 967,
'psi': 968, 'psi': 968,
'omega': 969, 'omega': 969,
'thetasym': 977, 'thetasym': 977,
'upsih': 978, 'upsih': 978,
'piv': 982, 'piv': 982,
'bull': 8226, 'bull': 8226,
'hellip': 8230, 'hellip': 8230,
'prime': 8242, 'prime': 8242,
'Prime': 8243, 'Prime': 8243,
'oline': 8254, 'oline': 8254,
'frasl': 8260, 'frasl': 8260,
'ensp': 8194, 'ensp': 8194,
'emsp': 8195, 'emsp': 8195,
'thinsp': 8201, 'thinsp': 8201,
'zwnj': 8204, 'zwnj': 8204,
'zwj': 8205, 'zwj': 8205,
'lrm': 8206, 'lrm': 8206,
'rlm': 8207, 'rlm': 8207,
'ndash': 8211, 'ndash': 8211,
'mdash': 8212, 'mdash': 8212,
'lsquo': 8216, 'lsquo': 8216,
'rsquo': 8217, 'rsquo': 8217,
'sbquo': 8218, 'sbquo': 8218,
'ldquo': 8220, 'ldquo': 8220,
'rdquo': 8221, 'rdquo': 8221,
'bdquo': 8222, 'bdquo': 8222,
'dagger': 8224, 'dagger': 8224,
'Dagger': 8225, 'Dagger': 8225,
'permil': 8240, 'permil': 8240,
'lsaquo': 8249, 'lsaquo': 8249,
'rsaquo': 8250, 'rsaquo': 8250,
'euro': 8364, 'euro': 8364,
'weierp': 8472, 'weierp': 8472,
'image': 8465, 'image': 8465,
'real': 8476, 'real': 8476,
'trade': 8482, 'trade': 8482,
'alefsym': 8501, 'alefsym': 8501,
'larr': 8592, 'larr': 8592,
'uarr': 8593, 'uarr': 8593,
'rarr': 8594, 'rarr': 8594,
'darr': 8595, 'darr': 8595,
'harr': 8596, 'harr': 8596,
'crarr': 8629, 'crarr': 8629,
'lArr': 8656, 'lArr': 8656,
'uArr': 8657, 'uArr': 8657,
'rArr': 8658, 'rArr': 8658,
'dArr': 8659, 'dArr': 8659,
'hArr': 8660, 'hArr': 8660,
'forall': 8704, 'forall': 8704,
'part': 8706, 'part': 8706,
'exist': 8707, 'exist': 8707,
'empty': 8709, 'empty': 8709,
'nabla': 8711, 'nabla': 8711,
'isin': 8712, 'isin': 8712,
'notin': 8713, 'notin': 8713,
'ni': 8715, 'ni': 8715,
'prod': 8719, 'prod': 8719,
'sum': 8721, 'sum': 8721,
'minus': 8722, 'minus': 8722,
'lowast': 8727, 'lowast': 8727,
'radic': 8730, 'radic': 8730,
'prop': 8733, 'prop': 8733,
'infin': 8734, 'infin': 8734,
'ang': 8736, 'ang': 8736,
'and': 8743, 'and': 8743,
'or': 8744, 'or': 8744,
'cap': 8745, 'cap': 8745,
'cup': 8746, 'cup': 8746,
'int': 8747, 'int': 8747,
'there4': 8756, 'there4': 8756,
'sim': 8764, 'sim': 8764,
'cong': 8773, 'cong': 8773,
'asymp': 8776, 'asymp': 8776,
'ne': 8800, 'ne': 8800,
'equiv': 8801, 'equiv': 8801,
'le': 8804, 'le': 8804,
'ge': 8805, 'ge': 8805,
'sub': 8834, 'sub': 8834,
'sup': 8835, 'sup': 8835,
'nsub': 8836, 'nsub': 8836,
'sube': 8838, 'sube': 8838,
'supe': 8839, 'supe': 8839,
'oplus': 8853, 'oplus': 8853,
'otimes': 8855, 'otimes': 8855,
'perp': 8869, 'perp': 8869,
'sdot': 8901, 'sdot': 8901,
'lceil': 8968, 'lceil': 8968,
'rceil': 8969, 'rceil': 8969,
'lfloor': 8970, 'lfloor': 8970,
'rfloor': 8971, 'rfloor': 8971,
'lang': 9001, 'lang': 9001,
'rang': 9002, 'rang': 9002,
'loz': 9674, 'loz': 9674,
'spades': 9824, 'spades': 9824,
'clubs': 9827, 'clubs': 9827,
'hearts': 9829, 'hearts': 9829,
'diams': 9830, 'diams': 9830,
} }

View File

@ -26,7 +26,7 @@ try:
except ImportError: except ImportError:
LOGGER_HANDLER = logging.StreamHandler(sys.stdout) LOGGER_HANDLER = logging.StreamHandler(sys.stdout)
FORMATTER = logging.Formatter("\r[%(asctime)s] [%(levelname)s] %(message)s", "%H:%M:%S") FORMATTER = logging.Formatter(u"\r[%(asctime)s] [%(levelname)s] %(message)s", "%H:%M:%S")
LOGGER_HANDLER.setFormatter(FORMATTER) LOGGER_HANDLER.setFormatter(FORMATTER)
LOGGER.addHandler(LOGGER_HANDLER) LOGGER.addHandler(LOGGER_HANDLER)

View File

@ -17,110 +17,38 @@ import sys
import threading import threading
import urllib2 import urllib2
import urlparse import urlparse
from xml.etree.ElementTree import ElementTree
import lib.core.common import lib.core.common
import lib.core.threads import lib.core.threads
import lib.core.convert import lib.core.convert
from lib.controller.checks import checkConnection from lib.controller.checks import checkConnection
from lib.core.common import Backend from lib.core.common import Backend, boldifyMessage, dataToStdout, getPublicTypeMembers, extractRegexResult,\
from lib.core.common import boldifyMessage filterStringValue, findPageForms, getConsoleWidth, getFileItems, getFileType, getUnicode, isListLike,\
from lib.core.common import dataToStdout normalizePath, ntToPosixSlashes, openFile, parseTargetDirect, parseTargetUrl, paths, randomRange, randomStr,\
from lib.core.common import getPublicTypeMembers readInput, resetCookieJar, runningAsAdmin, sanitizeStr, setOptimize, singleTimeWarnMessage,\
from lib.core.common import extractRegexResult UnicodeRawConfigParser, urldecode, urlencode
from lib.core.common import filterStringValue from lib.core.data import conf, kb, logger, queries
from lib.core.common import findPageForms from lib.core.datatype import AttribDict, InjectionDict
from lib.core.common import getConsoleWidth
from lib.core.common import getFileItems
from lib.core.common import getFileType
from lib.core.common import getUnicode
from lib.core.common import isListLike
from lib.core.common import normalizePath
from lib.core.common import ntToPosixSlashes
from lib.core.common import openFile
from lib.core.common import parseTargetDirect
from lib.core.common import parseTargetUrl
from lib.core.common import paths
from lib.core.common import randomRange
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.common import resetCookieJar
from lib.core.common import runningAsAdmin
from lib.core.common import sanitizeStr
from lib.core.common import setOptimize
from lib.core.common import singleTimeWarnMessage
from lib.core.common import UnicodeRawConfigParser
from lib.core.common import urldecode
from lib.core.common import urlencode
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.datatype import AttribDict
from lib.core.datatype import InjectionDict
from lib.core.defaults import defaults from lib.core.defaults import defaults
from lib.core.dicts import DBMS_DICT from lib.core.dicts import DBMS_DICT
from lib.core.dicts import DUMP_REPLACEMENTS from lib.core.dicts import DUMP_REPLACEMENTS
from lib.core.enums import ADJUST_TIME_DELAY from lib.core.enums import ADJUST_TIME_DELAY, CUSTOM_LOGGING, DUMP_FORMAT, HTTPHEADER, HTTPMETHOD, MOBILES,\
from lib.core.enums import CUSTOM_LOGGING PAYLOAD, PRIORITY, PROXY_TYPE, REFLECTIVE_COUNTER, WIZARD
from lib.core.enums import DUMP_FORMAT from lib.core.exception import sqlmapConnectionException, sqlmapFilePathException, sqlmapGenericException,\
from lib.core.enums import HTTPHEADER sqlmapMissingDependence, sqlmapMissingMandatoryOptionException, sqlmapMissingPrivileges,\
from lib.core.enums import HTTPMETHOD sqlmapSilentQuitException, sqlmapSyntaxException, sqlmapUnsupportedDBMSException, sqlmapUserQuitException
from lib.core.enums import MOBILES from lib.core.log import FORMATTER, LOGGER_HANDLER
from lib.core.enums import PAYLOAD
from lib.core.enums import PRIORITY
from lib.core.enums import PROXY_TYPE
from lib.core.enums import REFLECTIVE_COUNTER
from lib.core.enums import WIZARD
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapMissingDependence
from lib.core.exception import sqlmapMissingMandatoryOptionException
from lib.core.exception import sqlmapMissingPrivileges
from lib.core.exception import sqlmapSilentQuitException
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapUnsupportedDBMSException
from lib.core.exception import sqlmapUserQuitException
from lib.core.log import FORMATTER
from lib.core.log import LOGGER_HANDLER
from lib.core.optiondict import optDict from lib.core.optiondict import optDict
from lib.core.purge import purge from lib.core.purge import purge
from lib.core.settings import ACCESS_ALIASES from lib.core.settings import ACCESS_ALIASES, BURP_REQUEST_REGEX, CODECS_LIST_PAGE, CRAWL_EXCLUDE_EXTENSIONS,\
from lib.core.settings import BURP_REQUEST_REGEX CUSTOM_INJECTION_MARK_CHAR, DB2_ALIASES, DEFAULT_GET_POST_DELIMITER, DEFAULT_PAGE_ENCODING,\
from lib.core.settings import CODECS_LIST_PAGE DEFAULT_TOR_HTTP_PORTS, DEFAULT_TOR_SOCKS_PORT, FIREBIRD_ALIASES, INJECT_HERE_MARK, IS_WIN,\
from lib.core.settings import CRAWL_EXCLUDE_EXTENSIONS LOCALHOST, MAXDB_ALIASES, MAX_NUMBER_OF_THREADS, MSSQL_ALIASES, MYSQL_ALIASES, NULL, ORACLE_ALIASES,\
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR PARAMETER_SPLITTING_REGEX, PGSQL_ALIASES, PYVERSION, SITE, SQLITE_ALIASES, SUPPORTED_DBMS, SUPPORTED_OS,\
from lib.core.settings import DB2_ALIASES SYBASE_ALIASES, TIME_DELAY_CANDIDATES, UNENCODED_ORIGINAL_VALUE, UNION_CHAR_REGEX, UNKNOWN_DBMS_VERSION,\
from lib.core.settings import DEFAULT_GET_POST_DELIMITER URI_INJECTABLE_REGEX, VERSION_STRING, WEBSCARAB_SPLITTER
from lib.core.settings import DEFAULT_PAGE_ENCODING
from lib.core.settings import DEFAULT_TOR_HTTP_PORTS
from lib.core.settings import DEFAULT_TOR_SOCKS_PORT
from lib.core.settings import FIREBIRD_ALIASES
from lib.core.settings import INJECT_HERE_MARK
from lib.core.settings import IS_WIN
from lib.core.settings import LOCALHOST
from lib.core.settings import MAXDB_ALIASES
from lib.core.settings import MAX_NUMBER_OF_THREADS
from lib.core.settings import MSSQL_ALIASES
from lib.core.settings import MYSQL_ALIASES
from lib.core.settings import NULL
from lib.core.settings import ORACLE_ALIASES
from lib.core.settings import PARAMETER_SPLITTING_REGEX
from lib.core.settings import PGSQL_ALIASES
from lib.core.settings import PYVERSION
from lib.core.settings import SITE
from lib.core.settings import SQLITE_ALIASES
from lib.core.settings import SUPPORTED_DBMS
from lib.core.settings import SUPPORTED_OS
from lib.core.settings import SYBASE_ALIASES
from lib.core.settings import TIME_DELAY_CANDIDATES
from lib.core.settings import UNENCODED_ORIGINAL_VALUE
from lib.core.settings import UNION_CHAR_REGEX
from lib.core.settings import UNKNOWN_DBMS_VERSION
from lib.core.settings import URI_INJECTABLE_REGEX
from lib.core.settings import VERSION_STRING
from lib.core.settings import WEBSCARAB_SPLITTER
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
from lib.core.update import update from lib.core.update import update
from lib.parse.configfile import configFileParser from lib.parse.configfile import configFileParser
@ -142,7 +70,7 @@ from thirdparty.colorama.initialise import init as coloramainit
from thirdparty.keepalive import keepalive from thirdparty.keepalive import keepalive
from thirdparty.oset.pyoset import oset from thirdparty.oset.pyoset import oset
from thirdparty.socks import socks from thirdparty.socks import socks
from xml.etree.ElementTree import ElementTree
authHandler = urllib2.BaseHandler() authHandler = urllib2.BaseHandler()
httpsHandler = HTTPSHandler() httpsHandler = HTTPSHandler()

View File

@ -6,202 +6,202 @@ See the file 'doc/COPYING' for copying permission
""" """
optDict = { optDict = {
# Format: # Format:
# Family: { "parameter name": "parameter datatype" }, # Family: { "parameter name": "parameter datatype" },
# Or: # Or:
# Family: { "parameter name": ("parameter datatype", "category name used for common outputs feature") }, # Family: { "parameter name": ("parameter datatype", "category name used for common outputs feature") },
"Target": { "Target": {
"direct": "string", "direct": "string",
"url": "string", "url": "string",
"logFile": "string", "logFile": "string",
"bulkFile": "string", "bulkFile": "string",
"requestFile": "string", "requestFile": "string",
"sessionFile": "string", "sessionFile": "string",
"googleDork": "string", "googleDork": "string",
"configFile": "string" "configFile": "string"
}, },
"Request": { "Request": {
"data": "string", "data": "string",
"pDel": "string", "pDel": "string",
"cookie": "string", "cookie": "string",
"loadCookies": "string", "loadCookies": "string",
"dropSetCookie": "boolean", "dropSetCookie": "boolean",
"agent": "string", "agent": "string",
"randomAgent": "boolean", "randomAgent": "boolean",
"rParam": "string", "rParam": "string",
"forceSSL": "boolean", "forceSSL": "boolean",
"host": "string", "host": "string",
"referer": "string", "referer": "string",
"headers": "string", "headers": "string",
"aType": "string", "aType": "string",
"aCred": "string", "aCred": "string",
"aCert": "string", "aCert": "string",
"proxy": "string", "proxy": "string",
"pCred": "string", "pCred": "string",
"ignoreProxy": "boolean", "ignoreProxy": "boolean",
"delay": "float", "delay": "float",
"timeout": "float", "timeout": "float",
"retries": "integer", "retries": "integer",
"scope": "string", "scope": "string",
"safUrl": "string", "safUrl": "string",
"saFreq": "integer", "saFreq": "integer",
"skipUrlEncode": "boolean", "skipUrlEncode": "boolean",
"evalCode": "string" "evalCode": "string"
}, },
"Optimization": { "Optimization": {
"optimize": "boolean", "optimize": "boolean",
"predictOutput": "boolean", "predictOutput": "boolean",
"keepAlive": "boolean", "keepAlive": "boolean",
"nullConnection": "boolean", "nullConnection": "boolean",
"threads": "integer" "threads": "integer"
}, },
"Injection": { "Injection": {
"testParameter": "string", "testParameter": "string",
"dbms": "string", "dbms": "string",
"os": "string", "os": "string",
"invalidBignum": "boolean", "invalidBignum": "boolean",
"invalidLogical": "boolean", "invalidLogical": "boolean",
"noCast": "boolean", "noCast": "boolean",
"noUnescape": "boolean", "noUnescape": "boolean",
"prefix": "string", "prefix": "string",
"suffix": "string", "suffix": "string",
"skip": "string", "skip": "string",
"tamper": "string" "tamper": "string"
}, },
"Detection": { "Detection": {
"level": "integer", "level": "integer",
"risk": "integer", "risk": "integer",
"string": "string", "string": "string",
"notString": "string", "notString": "string",
"regexp": "string", "regexp": "string",
"code": "integer", "code": "integer",
"textOnly": "boolean", "textOnly": "boolean",
"titles": "boolean" "titles": "boolean"
}, },
"Techniques": { "Techniques": {
"tech": "string", "tech": "string",
"timeSec": "integer", "timeSec": "integer",
"uCols": "string", "uCols": "string",
"uChar": "string", "uChar": "string",
"dnsName": "string", "dnsName": "string",
"secondOrder": "string" "secondOrder": "string"
}, },
"Fingerprint": { "Fingerprint": {
"extensiveFp": "boolean" "extensiveFp": "boolean"
}, },
"Enumeration": { "Enumeration": {
"getAll": "boolean", "getAll": "boolean",
"getBanner": ("boolean", "Banners"), "getBanner": ("boolean", "Banners"),
"getCurrentUser": ("boolean", "Users"), "getCurrentUser": ("boolean", "Users"),
"getCurrentDb": ("boolean", "Databases"), "getCurrentDb": ("boolean", "Databases"),
"getHostname": "boolean", "getHostname": "boolean",
"isDba": "boolean", "isDba": "boolean",
"getUsers": ("boolean", "Users"), "getUsers": ("boolean", "Users"),
"getPasswordHashes": ("boolean", "Passwords"), "getPasswordHashes": ("boolean", "Passwords"),
"getPrivileges": ("boolean", "Privileges"), "getPrivileges": ("boolean", "Privileges"),
"getRoles": ("boolean", "Roles"), "getRoles": ("boolean", "Roles"),
"getDbs": ("boolean", "Databases"), "getDbs": ("boolean", "Databases"),
"getTables": ("boolean", "Tables"), "getTables": ("boolean", "Tables"),
"getColumns": ("boolean", "Columns"), "getColumns": ("boolean", "Columns"),
"getSchema": "boolean", "getSchema": "boolean",
"getCount": "boolean", "getCount": "boolean",
"dumpTable": "boolean", "dumpTable": "boolean",
"dumpAll": "boolean", "dumpAll": "boolean",
"search": "boolean", "search": "boolean",
"db": "string", "db": "string",
"tbl": "string", "tbl": "string",
"col": "string", "col": "string",
"user": "string", "user": "string",
"excludeSysDbs": "boolean", "excludeSysDbs": "boolean",
"limitStart": "integer", "limitStart": "integer",
"limitStop": "integer", "limitStop": "integer",
"firstChar": "integer", "firstChar": "integer",
"lastChar": "integer", "lastChar": "integer",
"query": "string", "query": "string",
"sqlShell": "boolean", "sqlShell": "boolean",
"sqlFile": "string" "sqlFile": "string"
}, },
"Brute": { "Brute": {
"commonTables": "boolean", "commonTables": "boolean",
"commonColumns": "boolean" "commonColumns": "boolean"
}, },
"User-defined function": { "User-defined function": {
"udfInject": "boolean", "udfInject": "boolean",
"shLib": "string" "shLib": "string"
}, },
"File system": { "File system": {
"rFile": "string", "rFile": "string",
"wFile": "string", "wFile": "string",
"dFile": "string" "dFile": "string"
}, },
"Takeover": { "Takeover": {
"osCmd": "string", "osCmd": "string",
"osShell": "boolean", "osShell": "boolean",
"osPwn": "boolean", "osPwn": "boolean",
"osSmb": "boolean", "osSmb": "boolean",
"osBof": "boolean", "osBof": "boolean",
"privEsc": "boolean", "privEsc": "boolean",
"msfPath": "string", "msfPath": "string",
"tmpPath": "string" "tmpPath": "string"
}, },
"Windows": { "Windows": {
"regRead": "boolean", "regRead": "boolean",
"regAdd": "boolean", "regAdd": "boolean",
"regDel": "boolean", "regDel": "boolean",
"regKey": "string", "regKey": "string",
"regVal": "string", "regVal": "string",
"regData": "string", "regData": "string",
"regType": "string" "regType": "string"
}, },
"General": { "General": {
#"xmlFile": "string", #"xmlFile": "string",
"trafficFile": "string", "trafficFile": "string",
"batch": "boolean", "batch": "boolean",
"charset": "string", "charset": "string",
"checkTor": "boolean", "checkTor": "boolean",
"crawlDepth": "integer", "crawlDepth": "integer",
"csvDel": "string", "csvDel": "string",
"dbmsCred": "string", "dbmsCred": "string",
"dumpFormat": "string", "dumpFormat": "string",
"eta": "boolean", "eta": "boolean",
"flushSession": "boolean", "flushSession": "boolean",
"forms": "boolean", "forms": "boolean",
"freshQueries": "boolean", "freshQueries": "boolean",
"hexConvert": "boolean", "hexConvert": "boolean",
"oDir": "string", "oDir": "string",
"parseErrors": "boolean", "parseErrors": "boolean",
"updateAll": "boolean", "updateAll": "boolean",
"tor": "boolean", "tor": "boolean",
"torPort": "integer", "torPort": "integer",
"torType": "string", "torType": "string",
}, },
"Miscellaneous": { "Miscellaneous": {
"mnemonics": "string", "mnemonics": "string",
"answers": "string", "answers": "string",
"checkPayload": "boolean", "checkPayload": "boolean",
"cleanup": "boolean", "cleanup": "boolean",
"dependencies": "boolean", "dependencies": "boolean",
"disableColoring": "boolean", "disableColoring": "boolean",
"googlePage": "integer", "googlePage": "integer",
"mobile": "boolean", "mobile": "boolean",
"pageRank": "boolean", "pageRank": "boolean",
"smart": "boolean", "smart": "boolean",
"testFilter": "string", "testFilter": "string",
"wizard": "boolean", "wizard": "boolean",
"verbose": "integer" "verbose": "integer"
}, },
} }

View File

@ -25,9 +25,8 @@ class ProgressBar:
self.update() self.update()
def __convertSeconds(self, value): def __convertSeconds(self, value):
seconds = value minutes = value / 60
minutes = seconds / 60 seconds = value - (minutes * 60)
seconds = seconds - (minutes * 60)
return "%.2d:%.2d" % (minutes, seconds) return "%.2d:%.2d" % (minutes, seconds)

View File

@ -6,8 +6,7 @@ See the file 'doc/COPYING' for copying permission
""" """
from lib.core.data import logger from lib.core.data import logger
from lib.core.settings import IS_WIN from lib.core.settings import IS_WIN, PLATFORM
from lib.core.settings import PLATFORM
_readline = None _readline = None

View File

@ -9,9 +9,7 @@ import sqlite3
from extra.safe2bin.safe2bin import safechardecode from extra.safe2bin.safe2bin import safechardecode
from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.common import unsafeSQLIdentificatorNaming
from lib.core.exception import sqlmapGenericException from lib.core.exception import sqlmapGenericException, sqlmapValueException
from lib.core.exception import sqlmapMissingDependence
from lib.core.exception import sqlmapValueException
class Replication: class Replication:
""" """

View File

@ -8,8 +8,7 @@ See the file 'doc/COPYING' for copying permission
import os import os
import re import re
from subprocess import PIPE from subprocess import PIPE, Popen as execute
from subprocess import Popen as execute
def getRevisionNumber(): def getRevisionNumber():
""" """

View File

@ -7,21 +7,10 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.common import Backend from lib.core.common import Backend, Format, hashDBWrite
from lib.core.common import Format from lib.core.data import kb, logger
from lib.core.common import hashDBWrite from lib.core.enums import HASHDB_KEYS, OS
from lib.core.common import intersect
from lib.core.common import readInput
from lib.core.common import singleTimeWarnMessage
from lib.core.convert import base64pickle
from lib.core.convert import base64unpickle
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.enums import HASHDB_KEYS
from lib.core.enums import OS
from lib.core.settings import SUPPORTED_DBMS from lib.core.settings import SUPPORTED_DBMS
from lib.core.settings import UNKNOWN_DBMS_VERSION
def setDbms(dbms): def setDbms(dbms):
""" """

View File

@ -16,7 +16,7 @@ from lib.core.enums import DBMS_DIRECTORY_NAME
from lib.core.revision import getRevisionNumber from lib.core.revision import getRevisionNumber
# sqlmap version and site # sqlmap version and site
VERSION = "1.0-dev" VERSION = "1.0-dev" #TODO: Move to read from file
REVISION = getRevisionNumber() REVISION = getRevisionNumber()
VERSION_STRING = "sqlmap/%s%s" % (VERSION, "-%s" % REVISION if REVISION else "") VERSION_STRING = "sqlmap/%s%s" % (VERSION, "-%s" % REVISION if REVISION else "")
DESCRIPTION = "automatic SQL injection and database takeover tool" DESCRIPTION = "automatic SQL injection and database takeover tool"
@ -136,14 +136,17 @@ MYSQL_SYSTEM_DBS = ( "information_schema", "mysql" ) # Before
PGSQL_SYSTEM_DBS = ( "information_schema", "pg_catalog", "pg_toast" ) PGSQL_SYSTEM_DBS = ( "information_schema", "pg_catalog", "pg_toast" )
ORACLE_SYSTEM_DBS = ( "SYSTEM", "SYSAUX", "SYS" ) # These are TABLESPACE_NAME ORACLE_SYSTEM_DBS = ( "SYSTEM", "SYSAUX", "SYS" ) # These are TABLESPACE_NAME
SQLITE_SYSTEM_DBS = ( "sqlite_master", "sqlite_temp_master" ) SQLITE_SYSTEM_DBS = ( "sqlite_master", "sqlite_temp_master" )
ACCESS_SYSTEM_DBS = ( "MSysAccessObjects", "MSysACEs", "MSysObjects", "MSysQueries", "MSysRelationships", "MSysAccessStorage",\ ACCESS_SYSTEM_DBS = (
"MSysAccessXML", "MSysModules", "MSysModules2" ) "MSysAccessObjects", "MSysACEs", "MSysObjects", "MSysQueries", "MSysRelationships", "MSysAccessStorage",\
FIREBIRD_SYSTEM_DBS = ( "RDB$BACKUP_HISTORY", "RDB$CHARACTER_SETS", "RDB$CHECK_CONSTRAINTS", "RDB$COLLATIONS", "RDB$DATABASE",\ "MSysAccessXML", "MSysModules", "MSysModules2" )
"RDB$DEPENDENCIES", "RDB$EXCEPTIONS", "RDB$FIELDS", "RDB$FIELD_DIMENSIONS", " RDB$FILES", "RDB$FILTERS",\ FIREBIRD_SYSTEM_DBS = (
"RDB$FORMATS", "RDB$FUNCTIONS", "RDB$FUNCTION_ARGUMENTS", "RDB$GENERATORS", "RDB$INDEX_SEGMENTS", "RDB$INDICES",\ "RDB$BACKUP_HISTORY", "RDB$CHARACTER_SETS", "RDB$CHECK_CONSTRAINTS", "RDB$COLLATIONS", "RDB$DATABASE",\
"RDB$LOG_FILES", "RDB$PAGES", "RDB$PROCEDURES", "RDB$PROCEDURE_PARAMETERS", "RDB$REF_CONSTRAINTS", "RDB$RELATIONS",\ "RDB$DEPENDENCIES", "RDB$EXCEPTIONS", "RDB$FIELDS", "RDB$FIELD_DIMENSIONS", " RDB$FILES", "RDB$FILTERS",\
"RDB$RELATION_CONSTRAINTS", "RDB$RELATION_FIELDS", "RDB$ROLES", "RDB$SECURITY_CLASSES", "RDB$TRANSACTIONS", "RDB$TRIGGERS",\ "RDB$FORMATS", "RDB$FUNCTIONS", "RDB$FUNCTION_ARGUMENTS", "RDB$GENERATORS", "RDB$INDEX_SEGMENTS", "RDB$INDICES",\
"RDB$TRIGGER_MESSAGES", "RDB$TYPES", "RDB$USER_PRIVILEGES", "RDB$VIEW_RELATIONS" ) "RDB$LOG_FILES", "RDB$PAGES", "RDB$PROCEDURES", "RDB$PROCEDURE_PARAMETERS", "RDB$REF_CONSTRAINTS", "RDB$RELATIONS",\
"RDB$RELATION_CONSTRAINTS", "RDB$RELATION_FIELDS", "RDB$ROLES", "RDB$SECURITY_CLASSES", "RDB$TRANSACTIONS",
"RDB$TRIGGERS",\
"RDB$TRIGGER_MESSAGES", "RDB$TYPES", "RDB$USER_PRIVILEGES", "RDB$VIEW_RELATIONS" )
MAXDB_SYSTEM_DBS = ( "SYSINFO", "DOMAIN" ) MAXDB_SYSTEM_DBS = ( "SYSINFO", "DOMAIN" )
SYBASE_SYSTEM_DBS = ( "master", "model", "sybsystemdb", "sybsystemprocs" ) SYBASE_SYSTEM_DBS = ( "master", "model", "sybsystemdb", "sybsystemprocs" )
DB2_SYSTEM_DBS = ( "NULLID", "SQLJ", "SYSCAT", "SYSFUN", "SYSIBM", "SYSIBMADM", "SYSIBMINTERNAL", "SYSIBMTS",\ DB2_SYSTEM_DBS = ( "NULLID", "SQLJ", "SYSCAT", "SYSFUN", "SYSIBM", "SYSIBMADM", "SYSIBMINTERNAL", "SYSIBMTS",\
@ -160,7 +163,8 @@ MAXDB_ALIASES = ( "maxdb", "sap maxdb", "sap db" )
SYBASE_ALIASES = ( "sybase", "sybase sql server" ) SYBASE_ALIASES = ( "sybase", "sybase sql server" )
DB2_ALIASES = ( "db2", "ibm db2", "ibmdb2" ) DB2_ALIASES = ( "db2", "ibm db2", "ibmdb2" )
DBMS_DIRECTORY_DICT = dict((getattr(DBMS, _), getattr(DBMS_DIRECTORY_NAME, _)) for _ in dir(DBMS) if not _.startswith("_")) DBMS_DIRECTORY_DICT = dict(
(getattr(DBMS, _), getattr(DBMS_DIRECTORY_NAME, _)) for _ in dir(DBMS) if not _.startswith("_"))
SUPPORTED_DBMS = MSSQL_ALIASES + MYSQL_ALIASES + PGSQL_ALIASES + ORACLE_ALIASES + SQLITE_ALIASES + ACCESS_ALIASES + FIREBIRD_ALIASES + MAXDB_ALIASES + SYBASE_ALIASES + DB2_ALIASES SUPPORTED_DBMS = MSSQL_ALIASES + MYSQL_ALIASES + PGSQL_ALIASES + ORACLE_ALIASES + SQLITE_ALIASES + ACCESS_ALIASES + FIREBIRD_ALIASES + MAXDB_ALIASES + SYBASE_ALIASES + DB2_ALIASES
SUPPORTED_OS = ( "linux", "windows" ) SUPPORTED_OS = ( "linux", "windows" )
@ -171,38 +175,38 @@ HOST_ALIASES = ( "host", )
# Items displayed in basic help (-h) output # Items displayed in basic help (-h) output
BASIC_HELP_ITEMS = ( BASIC_HELP_ITEMS = (
"url", "url",
"googleDork", "googleDork",
"data", "data",
"cookie", "cookie",
"randomAgent", "randomAgent",
"proxy", "proxy",
"testParameter", "testParameter",
"dbms", "dbms",
"level", "level",
"risk", "risk",
"tech", "tech",
"getAll", "getAll",
"getBanner", "getBanner",
"getCurrentUser", "getCurrentUser",
"getCurrentDb", "getCurrentDb",
"getPasswordHashes", "getPasswordHashes",
"getTables", "getTables",
"getColumns", "getColumns",
"getSchema", "getSchema",
"dumpTable", "dumpTable",
"dumpAll", "dumpAll",
"db", "db",
"tbl", "tbl",
"col", "col",
"osShell", "osShell",
"osPwn", "osPwn",
"batch", "batch",
"checkTor", "checkTor",
"flushSession", "flushSession",
"tor", "tor",
"wizard" "wizard"
) )
# String representation for NULL value # String representation for NULL value
NULL = "NULL" NULL = "NULL"
@ -215,11 +219,11 @@ CURRENT_DB = "CD"
# Regular expressions used for parsing error messages (--parse-errors) # Regular expressions used for parsing error messages (--parse-errors)
ERROR_PARSING_REGEXES = ( ERROR_PARSING_REGEXES = (
r"<b>[^<]*(fatal|error|warning|exception)[^<]*</b>:?\s*(?P<result>.+?)<br\s*/?\s*>", r"<b>[^<]*(fatal|error|warning|exception)[^<]*</b>:?\s*(?P<result>.+?)<br\s*/?\s*>",
r"(?m)^(fatal|error|warning|exception):?\s*(?P<result>.+?)$", r"(?m)^(fatal|error|warning|exception):?\s*(?P<result>.+?)$",
r"<li>Error Type:<br>(?P<result>.+?)</li>", r"<li>Error Type:<br>(?P<result>.+?)</li>",
r"error '[0-9a-f]{8}'((<[^>]+>)|\s)+(?P<result>[^<>]+)" r"error '[0-9a-f]{8}'((<[^>]+>)|\s)+(?P<result>[^<>]+)"
) )
# Regular expression used for parsing charset info from meta html headers # Regular expression used for parsing charset info from meta html headers
META_CHARSET_REGEX = r'(?si)<head>.*<meta http-equiv="?content-type"?[^>]+charset=(?P<result>[^">]+).*</head>' META_CHARSET_REGEX = r'(?si)<head>.*<meta http-equiv="?content-type"?[^>]+charset=(?P<result>[^">]+).*</head>'
@ -231,7 +235,9 @@ META_REFRESH_REGEX = r'(?si)<head>.*<meta http-equiv="?refresh"?[^>]+content="?[
EMPTY_FORM_FIELDS_REGEX = r'(&|\A)(?P<result>[^=]+=(&|\Z))' EMPTY_FORM_FIELDS_REGEX = r'(&|\A)(?P<result>[^=]+=(&|\Z))'
# Reference: http://www.cs.ru.nl/bachelorscripties/2010/Martin_Devillers___0437999___Analyzing_password_strength.pdf # Reference: http://www.cs.ru.nl/bachelorscripties/2010/Martin_Devillers___0437999___Analyzing_password_strength.pdf
COMMON_PASSWORD_SUFFIXES = ("1", "123", "2", "12", "3", "13", "7", "11", "5", "22", "23", "01", "4", "07", "21", "14", "10", "06", "08", "8", "15", "69", "16", "6", "18") COMMON_PASSWORD_SUFFIXES = (
"1", "123", "2", "12", "3", "13", "7", "11", "5", "22", "23", "01", "4", "07", "21", "14", "10", "06", "08", "8", "15",
"69", "16", "6", "18")
# Reference: http://www.the-interweb.com/serendipity/index.php?/archives/94-A-brief-analysis-of-40,000-leaked-MySpace-passwords.html # Reference: http://www.the-interweb.com/serendipity/index.php?/archives/94-A-brief-analysis-of-40,000-leaked-MySpace-passwords.html
COMMON_PASSWORD_SUFFIXES += ("!", ".", "*", "!!", "?", ";", "..", "!!!", ",", "@") COMMON_PASSWORD_SUFFIXES += ("!", ".", "*", "!!", "?", ";", "..", "!!!", ",", "@")
@ -279,7 +285,9 @@ MYSQL_ERROR_CHUNK_LENGTH = 50
MSSQL_ERROR_CHUNK_LENGTH = 100 MSSQL_ERROR_CHUNK_LENGTH = 100
# Do not unescape the injected statement if it contains any of the following SQL words # Do not unescape the injected statement if it contains any of the following SQL words
EXCLUDE_UNESCAPE = ("WAITFOR DELAY ", " INTO DUMPFILE ", " INTO OUTFILE ", "CREATE ", "BULK ", "EXEC ", "RECONFIGURE ", "DECLARE ", "'%s'" % CHAR_INFERENCE_MARK) EXCLUDE_UNESCAPE = (
"WAITFOR DELAY ", " INTO DUMPFILE ", " INTO OUTFILE ", "CREATE ", "BULK ", "EXEC ", "RECONFIGURE ", "DECLARE ",
"'%s'" % CHAR_INFERENCE_MARK)
# Mark used for replacement of reflected values # Mark used for replacement of reflected values
REFLECTED_VALUE_MARKER = "__REFLECTED_VALUE__" REFLECTED_VALUE_MARKER = "__REFLECTED_VALUE__"
@ -312,7 +320,9 @@ MAX_INT = sys.maxint
DEPRECATED_OPTIONS = ("--replicate",) DEPRECATED_OPTIONS = ("--replicate",)
# Parameters to be ignored in detection phase (upper case) # Parameters to be ignored in detection phase (upper case)
IGNORE_PARAMETERS = ("__VIEWSTATE", "__VIEWSTATEENCRYPTED", "__EVENTARGUMENT", "__EVENTTARGET", "__EVENTVALIDATION", "ASPSESSIONID", "ASP.NET_SESSIONID", "JSESSIONID", "CFID", "CFTOKEN") IGNORE_PARAMETERS = (
"__VIEWSTATE", "__VIEWSTATEENCRYPTED", "__EVENTARGUMENT", "__EVENTTARGET", "__EVENTVALIDATION", "ASPSESSIONID",
"ASP.NET_SESSIONID", "JSESSIONID", "CFID", "CFTOKEN")
# Regular expression used for recognition of ASP.NET control parameters # Regular expression used for recognition of ASP.NET control parameters
ASP_NET_CONTROL_REGEX = r"(?i)\Actl\d+\$" ASP_NET_CONTROL_REGEX = r"(?i)\Actl\d+\$"
@ -343,7 +353,9 @@ LOW_TEXT_PERCENT = 20
# These MySQL keywords can't go (alone) into versioned comment form (/*!...*/) # These MySQL keywords can't go (alone) into versioned comment form (/*!...*/)
# Reference: http://dev.mysql.com/doc/refman/5.1/en/function-resolution.html # Reference: http://dev.mysql.com/doc/refman/5.1/en/function-resolution.html
IGNORE_SPACE_AFFECTED_KEYWORDS = ("CAST", "COUNT", "EXTRACT", "GROUP_CONCAT", "MAX", "MID", "MIN", "SESSION_USER", "SUBSTR", "SUBSTRING", "SUM", "SYSTEM_USER", "TRIM") IGNORE_SPACE_AFFECTED_KEYWORDS = (
"CAST", "COUNT", "EXTRACT", "GROUP_CONCAT", "MAX", "MID", "MIN", "SESSION_USER", "SUBSTR", "SUBSTRING", "SUM",
"SYSTEM_USER", "TRIM")
LEGAL_DISCLAIMER = "Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program" LEGAL_DISCLAIMER = "Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program"
@ -363,7 +375,9 @@ DUMMY_SQL_INJECTION_CHARS = ";()'"
DUMMY_USER_INJECTION = r"(?i)[^\w](AND|OR)\s+[^\s]+[=><]" DUMMY_USER_INJECTION = r"(?i)[^\w](AND|OR)\s+[^\s]+[=><]"
# Extensions skipped by crawler # Extensions skipped by crawler
CRAWL_EXCLUDE_EXTENSIONS = ("gif","jpg","jar","tif","bmp","war","ear","mpg","wmv","mpeg","scm","iso","dmp","dll","cab","so","avi","bin","exe","iso","tar","png","pdf","ps","mp3","zip","rar","gz") CRAWL_EXCLUDE_EXTENSIONS = (
"gif", "jpg", "jar", "tif", "bmp", "war", "ear", "mpg", "wmv", "mpeg", "scm", "iso", "dmp", "dll", "cab", "so", "avi",
"bin", "exe", "iso", "tar", "png", "pdf", "ps", "mp3", "zip", "rar", "gz")
# Template used for common table existence check # Template used for common table existence check
BRUTE_TABLE_EXISTS_TEMPLATE = "EXISTS(SELECT %d FROM %s)" BRUTE_TABLE_EXISTS_TEMPLATE = "EXISTS(SELECT %d FROM %s)"
@ -402,7 +416,9 @@ UNION_CHAR_REGEX = r'\A\w+\Z'
UNENCODED_ORIGINAL_VALUE = 'original' UNENCODED_ORIGINAL_VALUE = 'original'
# Common column names containing usernames (used for hash cracking in some cases) # Common column names containing usernames (used for hash cracking in some cases)
COMMON_USER_COLUMNS = ('user', 'username', 'user_name', 'benutzername', 'benutzer', 'utilisateur', 'usager', 'consommateur', 'utente', 'utilizzatore', 'usufrutuario', 'korisnik', 'usuario', 'consumidor') COMMON_USER_COLUMNS = (
'user', 'username', 'user_name', 'benutzername', 'benutzer', 'utilisateur', 'usager', 'consommateur', 'utente',
'utilizzatore', 'usufrutuario', 'korisnik', 'usuario', 'consumidor')
# Default delimiter in GET/POST values # Default delimiter in GET/POST values
DEFAULT_GET_POST_DELIMITER = '&' DEFAULT_GET_POST_DELIMITER = '&'
@ -420,7 +436,7 @@ HASHDB_FLUSH_RETRIES = 3
HASHDB_MILESTONE_VALUE = "cAWxkLYCQT" # r5129 "".join(random.sample(string.letters, 10)) HASHDB_MILESTONE_VALUE = "cAWxkLYCQT" # r5129 "".join(random.sample(string.letters, 10))
# Warn user of possible delay due to large page dump in full UNION query injections # Warn user of possible delay due to large page dump in full UNION query injections
LARGE_OUTPUT_THRESHOLD = 1024**2 LARGE_OUTPUT_THRESHOLD = 1024 ** 2
# On huge tables there is a considerable slowdown if every row retrieval requires ORDER BY (most noticable in table dumping using ERROR injections) # On huge tables there is a considerable slowdown if every row retrieval requires ORDER BY (most noticable in table dumping using ERROR injections)
SLOW_ORDER_COUNT_THRESHOLD = 10000 SLOW_ORDER_COUNT_THRESHOLD = 10000
@ -471,7 +487,8 @@ GENERIC_DOC_ROOT_DIRECTORY_NAMES = ("htdocs", "wwwroot", "www")
MAX_HELP_OPTION_LENGTH = 18 MAX_HELP_OPTION_LENGTH = 18
# Strings for detecting formatting errors # Strings for detecting formatting errors
FORMAT_EXCEPTION_STRINGS = ("Type mismatch", "Error converting", "Failed to convert", "System.FormatException", "java.lang.NumberFormatException") FORMAT_EXCEPTION_STRINGS = (
"Type mismatch", "Error converting", "Failed to convert", "System.FormatException", "java.lang.NumberFormatException")
# Regular expression used for extracting ASP.NET view state values # Regular expression used for extracting ASP.NET view state values
VIEWSTATE_REGEX = r'(?i)(?P<name>__VIEWSTATE[^"]*)[^>]+value="(?P<result>[^"]+)' VIEWSTATE_REGEX = r'(?i)(?P<name>__VIEWSTATE[^"]*)[^>]+value="(?P<result>[^"]+)'

View File

@ -11,8 +11,7 @@ import rlcompleter
from lib.core import readlineng as readline from lib.core import readlineng as readline
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.data import logger from lib.core.data import logger, paths
from lib.core.data import paths
from lib.core.enums import OS from lib.core.enums import OS
def saveHistory(): def saveHistory():

View File

@ -5,7 +5,6 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
import binascii
import codecs import codecs
import os import os
import re import re
@ -13,47 +12,18 @@ import tempfile
import time import time
import urlparse import urlparse
from lib.core.common import Backend from lib.core.common import Backend, hashDBRetrieve, intersect, paramToDict, readInput, resetCookieJar, urldecode
from lib.core.common import hashDBRetrieve from lib.core.data import cmdLineOptions, conf, kb, logger, paths
from lib.core.common import intersect
from lib.core.common import paramToDict
from lib.core.common import readInput
from lib.core.common import resetCookieJar
from lib.core.common import urldecode
from lib.core.data import cmdLineOptions
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.dicts import DBMS_DICT from lib.core.dicts import DBMS_DICT
from lib.core.dump import dumper from lib.core.dump import dumper
from lib.core.enums import HASHDB_KEYS from lib.core.enums import HASHDB_KEYS, HTTPHEADER, HTTPMETHOD, PLACE, POST_HINT
from lib.core.enums import HTTPHEADER from lib.core.exception import sqlmapFilePathException, sqlmapGenericException, sqlmapMissingPrivileges,\
from lib.core.enums import HTTPMETHOD sqlmapSyntaxException, sqlmapUserQuitException
from lib.core.enums import PLACE
from lib.core.enums import POST_HINT from lib.core.option import __setDBMS, __setKnowledgeBaseAttributes, __setAuthCred
from lib.core.exception import sqlmapFilePathException from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR, HOST_ALIASES, JSON_RECOGNITION_REGEX,\
from lib.core.exception import sqlmapGenericException MULTIPART_RECOGNITION_REGEX, REFERER_ALIASES, RESULTS_FILE_FORMAT, SOAP_RECOGNITION_REGEX,\
from lib.core.exception import sqlmapMissingPrivileges SUPPORTED_DBMS, UNICODE_ENCODING, UNKNOWN_DBMS_VERSION, URI_INJECTABLE_REGEX, USER_AGENT_ALIASES
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapUserQuitException
from lib.core.option import authHandler
from lib.core.option import __setDBMS
from lib.core.option import __setKnowledgeBaseAttributes
from lib.core.option import __setAuthCred
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
from lib.core.settings import HOST_ALIASES
from lib.core.settings import JSON_RECOGNITION_REGEX
from lib.core.settings import MULTIPART_RECOGNITION_REGEX
from lib.core.settings import REFERER_ALIASES
from lib.core.settings import RESULTS_FILE_FORMAT
from lib.core.settings import SOAP_RECOGNITION_REGEX
from lib.core.settings import SUPPORTED_DBMS
from lib.core.settings import UNENCODED_ORIGINAL_VALUE
from lib.core.settings import UNICODE_ENCODING
from lib.core.settings import UNKNOWN_DBMS_VERSION
from lib.core.settings import URI_INJECTABLE_REGEX
from lib.core.settings import USER_AGENT_ALIASES
from lib.utils.hashdb import HashDB from lib.utils.hashdb import HashDB
from lib.core.xmldump import dumper as xmldumper from lib.core.xmldump import dumper as xmldumper
from thirdparty.odict.odict import OrderedDict from thirdparty.odict.odict import OrderedDict

View File

@ -14,15 +14,9 @@ import tempfile
import time import time
from lib.controller.controller import start from lib.controller.controller import start
from lib.core.common import beep from lib.core.common import beep, clearConsoleLine, dataToStdout, readXmlFile
from lib.core.common import clearConsoleLine from lib.core.data import conf, logger, paths
from lib.core.common import dataToStdout from lib.core.option import init, __setVerbosity
from lib.core.common import readXmlFile
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.option import init
from lib.core.option import __setVerbosity
from lib.core.optiondict import optDict from lib.core.optiondict import optDict
from lib.parse.cmdline import cmdLineParser from lib.parse.cmdline import cmdLineParser

View File

@ -12,16 +12,11 @@ import traceback
from thread import error as threadError from thread import error as threadError
from lib.core.data import conf from lib.core.data import conf, kb, logger
from lib.core.data import kb
from lib.core.data import logger
from lib.core.datatype import AttribDict from lib.core.datatype import AttribDict
from lib.core.enums import PAYLOAD from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapConnectionException from lib.core.exception import sqlmapConnectionException, sqlmapThreadException, sqlmapValueException
from lib.core.exception import sqlmapThreadException from lib.core.settings import MAX_NUMBER_OF_THREADS, PYVERSION
from lib.core.exception import sqlmapValueException
from lib.core.settings import MAX_NUMBER_OF_THREADS
from lib.core.settings import PYVERSION
shared = AttribDict() shared = AttribDict()

View File

@ -7,7 +7,6 @@ See the file 'doc/COPYING' for copying permission
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.data import conf from lib.core.data import conf
from lib.core.data import kb
from lib.core.datatype import AttribDict from lib.core.datatype import AttribDict
from lib.core.settings import EXCLUDE_UNESCAPE from lib.core.settings import EXCLUDE_UNESCAPE

View File

@ -9,19 +9,14 @@ import os
import re import re
import time import time
from subprocess import PIPE from subprocess import PIPE, Popen as execute
from subprocess import Popen as execute
from lib.core.common import dataToStdout from lib.core.common import dataToStdout
from lib.core.common import getUnicode
from lib.core.data import conf from lib.core.data import conf
from lib.core.data import logger from lib.core.data import logger
from lib.core.data import paths from lib.core.data import paths
from lib.core.revision import getRevisionNumber from lib.core.revision import getRevisionNumber
from lib.core.settings import GIT_REPOSITORY from lib.core.settings import GIT_REPOSITORY, IS_WIN
from lib.core.settings import IS_WIN
from lib.core.settings import REVISION
from lib.core.settings import UNICODE_ENCODING
from lib.core.subprocessng import pollProcess from lib.core.subprocessng import pollProcess
def update(): def update():

View File

@ -8,9 +8,7 @@ import xml
import xml.sax.saxutils as saxutils import xml.sax.saxutils as saxutils
from lib.core.common import getUnicode from lib.core.common import getUnicode
from lib.core.data import conf from lib.core.data import conf, kb, logger
from lib.core.data import kb
from lib.core.data import logger
from lib.core.exception import sqlmapFilePathException from lib.core.exception import sqlmapFilePathException
from lib.core.settings import UNICODE_ENCODING from lib.core.settings import UNICODE_ENCODING
from thirdparty.prettyprint import prettyprint from thirdparty.prettyprint import prettyprint
@ -32,7 +30,7 @@ DB_TABLE_ELEM_NAME = "DBTable"
IS_DBA_ELEM_NAME = "isDBA" IS_DBA_ELEM_NAME = "isDBA"
FILE_CONTENT_ELEM_NAME = "FileContent" FILE_CONTENT_ELEM_NAME = "FileContent"
DB_ATTR = "db" DB_ATTR = "db"
UNKNOWN_COLUMN_TYPE= "unknown" UNKNOWN_COLUMN_TYPE = "unknown"
USER_SETTINGS_ELEM_NAME = "UserSettings" USER_SETTINGS_ELEM_NAME = "UserSettings"
USER_SETTING_ELEM_NAME = "UserSetting" USER_SETTING_ELEM_NAME = "UserSetting"
USERS_ELEM_NAME = "Users" USERS_ELEM_NAME = "Users"
@ -72,7 +70,7 @@ XMLNS_ATTR = "xmlns:xsi"
SCHEME_NAME = "sqlmap.xsd" SCHEME_NAME = "sqlmap.xsd"
SCHEME_NAME_ATTR = "xsi:noNamespaceSchemaLocation" SCHEME_NAME_ATTR = "xsi:noNamespaceSchemaLocation"
CHARACTERS_TO_ENCODE = range(32) + range(127, 256) CHARACTERS_TO_ENCODE = range(32) + range(127, 256)
ENTITIES = {'"':'&quot;',"'":"&apos;"} ENTITIES = {'"': '&quot;', "'": "&apos;"}
class XMLDump: class XMLDump:
''' '''
@ -86,7 +84,7 @@ class XMLDump:
self.__root = None self.__root = None
self.__doc = Document() self.__doc = Document()
def __addToRoot(self,element): def __addToRoot(self, element):
''' '''
Adds element to the root element Adds element to the root element
''' '''
@ -105,36 +103,36 @@ class XMLDump:
kb.dataOutputFlag = True kb.dataOutputFlag = True
def __getRootChild(self,elemName): def __getRootChild(self, elemName):
''' '''
Returns the child of the root with the described name Returns the child of the root with the described name
''' '''
elements = self.__root.getElementsByTagName(elemName) elements = self.__root.getElementsByTagName(elemName)
if elements : if elements:
return elements[0] return elements[0]
return elements return elements
def __createTextNode(self,data): def __createTextNode(self, data):
''' '''
Creates a text node with utf8 data inside. Creates a text node with utf8 data inside.
The text is escaped to an fit the xml text Format. The text is escaped to an fit the xml text Format.
''' '''
if data is None : if data is None:
return self.__doc.createTextNode(u'') return self.__doc.createTextNode(u'')
else : else:
escaped_data = saxutils.escape(data, ENTITIES) escaped_data = saxutils.escape(data, ENTITIES)
return self.__doc.createTextNode(escaped_data) return self.__doc.createTextNode(escaped_data)
def __createAttribute(self,attrName,attrValue): def __createAttribute(self, attrName, attrValue):
''' '''
Creates an attribute node with utf8 data inside. Creates an attribute node with utf8 data inside.
The text is escaped to an fit the xml text Format. The text is escaped to an fit the xml text Format.
''' '''
attr = self.__doc.createAttribute(attrName) attr = self.__doc.createAttribute(attrName)
if attrValue is None : if attrValue is None:
attr.nodeValue = u'' attr.nodeValue = u''
else : else:
attr.nodeValue = getUnicode(attrValue) attr.nodeValue = getUnicode(attrValue)
return attr return attr
@ -153,7 +151,7 @@ class XMLDump:
if data: if data:
data = self.__formatString(data) data = self.__formatString(data)
else : else:
data = "" data = ""
elem = self.__doc.createElement(MESSAGE_ELEM) elem = self.__doc.createElement(MESSAGE_ELEM)
@ -168,7 +166,6 @@ class XMLDump:
lstElem = self.__doc.createElement(LST_ELEM_NAME) lstElem = self.__doc.createElement(LST_ELEM_NAME)
lstElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header)) lstElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header))
if elements: if elements:
if sort: if sort:
try: try:
elements = set(elements) elements = set(elements)
@ -185,7 +182,7 @@ class XMLDump:
memberElem.appendChild(self.__createTextNode(element)) memberElem.appendChild(self.__createTextNode(element))
elif isinstance(element, (list, tuple, set)): elif isinstance(element, (list, tuple, set)):
memberElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, "list")) memberElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, "list"))
for e in element : for e in element:
memberElemStr = self.__doc.createElement(MEMBER_ELEM) memberElemStr = self.__doc.createElement(MEMBER_ELEM)
memberElemStr.setAttributeNode(self.__createAttribute(TYPE_ATTR, "string")) memberElemStr.setAttributeNode(self.__createAttribute(TYPE_ATTR, "string"))
memberElemStr.appendChild(self.__createTextNode(getUnicode(e))) memberElemStr.appendChild(self.__createTextNode(getUnicode(e)))
@ -196,7 +193,7 @@ class XMLDump:
self.__addToRoot(listsElem) self.__addToRoot(listsElem)
listsElem.appendChild(lstElem) listsElem.appendChild(lstElem)
def technic(self,technicType,data): def technic(self, technicType, data):
''' '''
Adds information about the technic used to extract data from the db Adds information about the technic used to extract data from the db
''' '''
@ -210,7 +207,7 @@ class XMLDump:
self.__addToRoot(technicsElem) self.__addToRoot(technicsElem)
technicsElem.appendChild(technicElem) technicsElem.appendChild(technicElem)
def banner(self,data): def banner(self, data):
''' '''
Adds information about the database banner to the xml. Adds information about the database banner to the xml.
The banner contains information about the type and the version of the database. The banner contains information about the type and the version of the database.
@ -219,7 +216,7 @@ class XMLDump:
bannerElem.appendChild(self.__createTextNode(data)) bannerElem.appendChild(self.__createTextNode(data))
self.__addToRoot(bannerElem) self.__addToRoot(bannerElem)
def currentUser(self,data): def currentUser(self, data):
''' '''
Adds information about the current database user to the xml Adds information about the current database user to the xml
''' '''
@ -228,7 +225,7 @@ class XMLDump:
currentUserElem.appendChild(textNode) currentUserElem.appendChild(textNode)
self.__addToRoot(currentUserElem) self.__addToRoot(currentUserElem)
def currentDb(self,data): def currentDb(self, data):
''' '''
Adds information about the current database is use to the xml Adds information about the current database is use to the xml
''' '''
@ -237,7 +234,7 @@ class XMLDump:
currentDBElem.appendChild(textNode) currentDBElem.appendChild(textNode)
self.__addToRoot(currentDBElem) self.__addToRoot(currentDBElem)
def dba(self,isDBA): def dba(self, isDBA):
''' '''
Adds information to the xml that indicates whether the user has DBA privileges Adds information to the xml that indicates whether the user has DBA privileges
''' '''
@ -245,7 +242,7 @@ class XMLDump:
isDBAElem.setAttributeNode(self.__createAttribute(VALUE_ATTR, getUnicode(isDBA))) isDBAElem.setAttributeNode(self.__createAttribute(VALUE_ATTR, getUnicode(isDBA)))
self.__addToRoot(isDBAElem) self.__addToRoot(isDBAElem)
def users(self,users): def users(self, users):
''' '''
Adds a list of the existing users to the xml Adds a list of the existing users to the xml
''' '''
@ -325,7 +322,7 @@ class XMLDump:
for db, tables in dbTables.items(): for db, tables in dbTables.items():
tables.sort(key=lambda x: x.lower()) tables.sort(key=lambda x: x.lower())
dbElem = self.__doc.createElement(DATABASE_ELEM_NAME) dbElem = self.__doc.createElement(DATABASE_ELEM_NAME)
dbElem.setAttributeNode(self.__createAttribute(NAME_ATTR,db)) dbElem.setAttributeNode(self.__createAttribute(NAME_ATTR, db))
dbTablesElem.appendChild(dbElem) dbTablesElem.appendChild(dbElem)
for table in tables: for table in tables:
tableElem = self.__doc.createElement(DB_TABLE_ELEM_NAME) tableElem = self.__doc.createElement(DB_TABLE_ELEM_NAME)
@ -361,7 +358,7 @@ class XMLDump:
colElem = self.__doc.createElement(COLUMN_ELEM_NAME) colElem = self.__doc.createElement(COLUMN_ELEM_NAME)
if colType is not None: if colType is not None:
colElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, colType)) colElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, colType))
else : else:
colElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, UNKNOWN_COLUMN_TYPE)) colElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, UNKNOWN_COLUMN_TYPE))
colElem.appendChild(self.__createTextNode(column)) colElem.appendChild(self.__createTextNode(column))
tableElem.appendChild(colElem) tableElem.appendChild(colElem)
@ -426,16 +423,16 @@ class XMLDump:
if tbl in printDbs[db]: if tbl in printDbs[db]:
printDbs[db][tbl][col] = dataType printDbs[db][tbl][col] = dataType
else: else:
printDbs[db][tbl] = { col: dataType } printDbs[db][tbl] = {col: dataType}
else: else:
printDbs[db] = {} printDbs[db] = {}
printDbs[db][tbl] = { col: dataType } printDbs[db][tbl] = {col: dataType}
continue continue
self.dbTableColumns(printDbs) self.dbTableColumns(printDbs)
def query(self,query,queryRes): def query(self, query, queryRes):
''' '''
Adds details of an executed query to the xml. Adds details of an executed query to the xml.
The query details are the query itself and it's results. The query details are the query itself and it's results.
@ -449,7 +446,7 @@ class XMLDump:
self.__addToRoot(queriesElem) self.__addToRoot(queriesElem)
queriesElem.appendChild(queryElem) queriesElem.appendChild(queryElem)
def registerValue(self,registerData): def registerValue(self, registerData):
''' '''
Adds information about an extracted registry key to the xml Adds information about an extracted registry key to the xml
''' '''
@ -474,8 +471,8 @@ class XMLDump:
''' '''
Initiates the xml file from the configuration. Initiates the xml file from the configuration.
''' '''
if (conf.xmlFile) : if (conf.xmlFile):
try : try:
self.__outputFile = conf.xmlFile self.__outputFile = conf.xmlFile
self.__root = None self.__root = None
@ -490,8 +487,8 @@ class XMLDump:
if self.__root is None: if self.__root is None:
self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME) self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
self.__root.setAttributeNode(self.__createAttribute(XMLNS_ATTR,NAME_SPACE_ATTR)) self.__root.setAttributeNode(self.__createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
self.__root.setAttributeNode(self.__createAttribute(SCHEME_NAME_ATTR,SCHEME_NAME)) self.__root.setAttributeNode(self.__createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
self.__doc.appendChild(self.__root) self.__doc.appendChild(self.__root)
except IOError: except IOError:
raise sqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile) raise sqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile)
@ -508,7 +505,7 @@ class XMLDump:
''' '''
if ((self.__outputFP is not None) and not(self.__outputFP.closed)): if ((self.__outputFP is not None) and not(self.__outputFP.closed)):
statusElem = self.__doc.createElement(STATUS_ELEM_NAME) statusElem = self.__doc.createElement(STATUS_ELEM_NAME)
statusElem.setAttributeNode(self.__createAttribute(SUCESS_ATTR,getUnicode(resultStatus))) statusElem.setAttributeNode(self.__createAttribute(SUCESS_ATTR, getUnicode(resultStatus)))
if not resultStatus: if not resultStatus:
errorElem = self.__doc.createElement(ERROR_ELEM_NAME) errorElem = self.__doc.createElement(ERROR_ELEM_NAME)
@ -525,6 +522,7 @@ class XMLDump:
self.__write(prettyprint.formatXML(self.__doc, encoding=UNICODE_ENCODING)) self.__write(prettyprint.formatXML(self.__doc, encoding=UNICODE_ENCODING))
self.__outputFP.close() self.__outputFP.close()
def closeDumper(status, msg=""): def closeDumper(status, msg=""):
""" """
Closes the dumper of the session Closes the dumper of the session

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -9,12 +9,8 @@ import re
from xml.sax.handler import ContentHandler from xml.sax.handler import ContentHandler
from lib.core.common import checkFile from lib.core.common import checkFile, Backend, parseXmlFile, sanitizeStr
from lib.core.common import Backend from lib.core.data import kb, paths
from lib.core.common import parseXmlFile
from lib.core.common import sanitizeStr
from lib.core.data import kb
from lib.core.data import paths
from lib.core.enums import DBMS from lib.core.enums import DBMS
from lib.parse.handler import FingerprintHandler from lib.parse.handler import FingerprintHandler

View File

@ -7,674 +7,666 @@ See the file 'doc/COPYING' for copying permission
import sys import sys
from optparse import OptionError from optparse import OptionError, OptionGroup, OptionParser, SUPPRESS_HELP
from optparse import OptionGroup
from optparse import OptionParser
from optparse import SUPPRESS_HELP
from lib.core.common import checkDeprecatedOptions from lib.core.common import checkDeprecatedOptions, expandMnemonics, getUnicode
from lib.core.common import expandMnemonics
from lib.core.common import getUnicode
from lib.core.data import logger from lib.core.data import logger
from lib.core.defaults import defaults from lib.core.defaults import defaults
from lib.core.settings import BASIC_HELP_ITEMS from lib.core.settings import BASIC_HELP_ITEMS, IS_WIN, MAX_HELP_OPTION_LENGTH
from lib.core.settings import IS_WIN
from lib.core.settings import MAX_HELP_OPTION_LENGTH
from lib.core.settings import VERSION_STRING
def cmdLineParser(): def cmdLineParser():
""" """
This function parses the command line parameters and arguments This function parses the command line parameters and arguments
""" """
usage = "%s%s [options]" % ("python " if not IS_WIN else "", \ usage = "%s%s [options]" % ("python " if not IS_WIN else "",\
"\"%s\"" % sys.argv[0] if " " in sys.argv[0] else sys.argv[0]) "\"%s\"" % sys.argv[0] if " " in sys.argv[0] else sys.argv[0])
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
try: try:
parser.add_option("--hh", dest="advancedHelp", parser.add_option("--hh", dest="advancedHelp",
action="store_true", action="store_true",
help="Show advanced help message and exit") help="Show advanced help message and exit")
parser.add_option("-v", dest="verbose", type="int", parser.add_option("-v", dest="verbose", type="int",
help="Verbosity level: 0-6 (default %d)" % defaults.verbose) help="Verbosity level: 0-6 (default %d)" % defaults.verbose)
# Target options # Target options
target = OptionGroup(parser, "Target", "At least one of these " target = OptionGroup(parser, "Target", "At least one of these "
"options has to be specified to set the source " "options has to be specified to set the source "
"to get target urls from") "to get target urls from")
target.add_option("-d", dest="direct", help="Direct " target.add_option("-d", dest="direct", help="Direct "
"connection to the database") "connection to the database")
target.add_option("-u", "--url", dest="url", help="Target url") target.add_option("-u", "--url", dest="url", help="Target url")
target.add_option("-l", dest="logFile", help="Parse targets from Burp " target.add_option("-l", dest="logFile", help="Parse targets from Burp "
"or WebScarab proxy logs") "or WebScarab proxy logs")
target.add_option("-m", dest="bulkFile", help="Scan multiple targets enlisted " target.add_option("-m", dest="bulkFile", help="Scan multiple targets enlisted "
"in a given textual file ") "in a given textual file ")
target.add_option("-r", dest="requestFile", target.add_option("-r", dest="requestFile",
help="Load HTTP request from a file") help="Load HTTP request from a file")
target.add_option("-s", dest="sessionFile", target.add_option("-s", dest="sessionFile",
help="Load session from a stored (.sqlite) file") help="Load session from a stored (.sqlite) file")
target.add_option("-g", dest="googleDork", target.add_option("-g", dest="googleDork",
help="Process Google dork results as target urls") help="Process Google dork results as target urls")
target.add_option("-c", dest="configFile", target.add_option("-c", dest="configFile",
help="Load options from a configuration INI file") help="Load options from a configuration INI file")
# Request options # Request options
request = OptionGroup(parser, "Request", "These options can be used " request = OptionGroup(parser, "Request", "These options can be used "
"to specify how to connect to the target url") "to specify how to connect to the target url")
request.add_option("--data", dest="data", request.add_option("--data", dest="data",
help="Data string to be sent through POST") help="Data string to be sent through POST")
request.add_option("--param-del", dest="pDel", request.add_option("--param-del", dest="pDel",
help="Character used for splitting parameter values") help="Character used for splitting parameter values")
request.add_option("--cookie", dest="cookie", request.add_option("--cookie", dest="cookie",
help="HTTP Cookie header") help="HTTP Cookie header")
request.add_option("--load-cookies", dest="loadCookies", request.add_option("--load-cookies", dest="loadCookies",
help="File containing cookies in Netscape/wget format") help="File containing cookies in Netscape/wget format")
request.add_option("--drop-set-cookie", dest="dropSetCookie", request.add_option("--drop-set-cookie", dest="dropSetCookie",
action="store_true", action="store_true",
help="Ignore Set-Cookie header from response") help="Ignore Set-Cookie header from response")
request.add_option("--user-agent", dest="agent", request.add_option("--user-agent", dest="agent",
help="HTTP User-Agent header") help="HTTP User-Agent header")
request.add_option("--random-agent", dest="randomAgent", request.add_option("--random-agent", dest="randomAgent",
action="store_true", action="store_true",
help="Use randomly selected HTTP User-Agent header") help="Use randomly selected HTTP User-Agent header")
request.add_option("--randomize", dest="rParam", request.add_option("--randomize", dest="rParam",
help="Randomly change value for given parameter(s)") help="Randomly change value for given parameter(s)")
request.add_option("--force-ssl", dest="forceSSL", request.add_option("--force-ssl", dest="forceSSL",
action="store_true", action="store_true",
help="Force usage of SSL/HTTPS requests") help="Force usage of SSL/HTTPS requests")
request.add_option("--host", dest="host", request.add_option("--host", dest="host",
help="HTTP Host header") help="HTTP Host header")
request.add_option("--referer", dest="referer", request.add_option("--referer", dest="referer",
help="HTTP Referer header") help="HTTP Referer header")
request.add_option("--headers", dest="headers", request.add_option("--headers", dest="headers",
help="Extra headers (e.g. \"Accept-Language: fr\\nETag: 123\")") help="Extra headers (e.g. \"Accept-Language: fr\\nETag: 123\")")
request.add_option("--auth-type", dest="aType", request.add_option("--auth-type", dest="aType",
help="HTTP authentication type " help="HTTP authentication type "
"(Basic, Digest or NTLM)") "(Basic, Digest or NTLM)")
request.add_option("--auth-cred", dest="aCred", request.add_option("--auth-cred", dest="aCred",
help="HTTP authentication credentials " help="HTTP authentication credentials "
"(name:password)") "(name:password)")
request.add_option("--auth-cert", dest="aCert", request.add_option("--auth-cert", dest="aCert",
help="HTTP authentication certificate (" help="HTTP authentication certificate ("
"key_file,cert_file)") "key_file,cert_file)")
request.add_option("--proxy", dest="proxy", request.add_option("--proxy", dest="proxy",
help="Use a HTTP proxy to connect to the target url") help="Use a HTTP proxy to connect to the target url")
request.add_option("--proxy-cred", dest="pCred", request.add_option("--proxy-cred", dest="pCred",
help="HTTP proxy authentication credentials " help="HTTP proxy authentication credentials "
"(name:password)") "(name:password)")
request.add_option("--ignore-proxy", dest="ignoreProxy", action="store_true", request.add_option("--ignore-proxy", dest="ignoreProxy", action="store_true",
help="Ignore system default HTTP proxy") help="Ignore system default HTTP proxy")
request.add_option("--delay", dest="delay", type="float", request.add_option("--delay", dest="delay", type="float",
help="Delay in seconds between each HTTP request") help="Delay in seconds between each HTTP request")
request.add_option("--timeout", dest="timeout", type="float", request.add_option("--timeout", dest="timeout", type="float",
help="Seconds to wait before timeout connection " help="Seconds to wait before timeout connection "
"(default %d)" % defaults.timeout) "(default %d)" % defaults.timeout)
request.add_option("--retries", dest="retries", type="int", request.add_option("--retries", dest="retries", type="int",
help="Retries when the connection timeouts " help="Retries when the connection timeouts "
"(default %d)" % defaults.retries) "(default %d)" % defaults.retries)
request.add_option("--scope", dest="scope", request.add_option("--scope", dest="scope",
help="Regexp to filter targets from provided proxy log") help="Regexp to filter targets from provided proxy log")
request.add_option("--safe-url", dest="safUrl", request.add_option("--safe-url", dest="safUrl",
help="Url address to visit frequently during testing") help="Url address to visit frequently during testing")
request.add_option("--safe-freq", dest="saFreq", type="int", request.add_option("--safe-freq", dest="saFreq", type="int",
help="Test requests between two visits to a given safe url") help="Test requests between two visits to a given safe url")
request.add_option("--skip-urlencode", dest="skipUrlEncode", request.add_option("--skip-urlencode", dest="skipUrlEncode",
action="store_true", action="store_true",
help="Skip URL encoding of payload data") help="Skip URL encoding of payload data")
request.add_option("--eval", dest="evalCode", request.add_option("--eval", dest="evalCode",
help="Evaluate provided Python code before the request (e.g. \"import hashlib;id2=hashlib.md5(id).hexdigest()\")") help="Evaluate provided Python code before the request (e.g. \"import hashlib;id2=hashlib.md5(id).hexdigest()\")")
# Optimization options # Optimization options
optimization = OptionGroup(parser, "Optimization", "These " optimization = OptionGroup(parser, "Optimization", "These "
"options can be used to optimize the " "options can be used to optimize the "
"performance of sqlmap") "performance of sqlmap")
optimization.add_option("-o", dest="optimize", optimization.add_option("-o", dest="optimize",
action="store_true", action="store_true",
help="Turn on all optimization switches") help="Turn on all optimization switches")
optimization.add_option("--predict-output", dest="predictOutput", action="store_true", optimization.add_option("--predict-output", dest="predictOutput", action="store_true",
help="Predict common queries output") help="Predict common queries output")
optimization.add_option("--keep-alive", dest="keepAlive", action="store_true", optimization.add_option("--keep-alive", dest="keepAlive", action="store_true",
help="Use persistent HTTP(s) connections") help="Use persistent HTTP(s) connections")
optimization.add_option("--null-connection", dest="nullConnection", action="store_true", optimization.add_option("--null-connection", dest="nullConnection", action="store_true",
help="Retrieve page length without actual HTTP response body") help="Retrieve page length without actual HTTP response body")
optimization.add_option("--threads", dest="threads", type="int", optimization.add_option("--threads", dest="threads", type="int",
help="Max number of concurrent HTTP(s) " help="Max number of concurrent HTTP(s) "
"requests (default %d)" % defaults.threads) "requests (default %d)" % defaults.threads)
# Injection options # Injection options
injection = OptionGroup(parser, "Injection", "These options can be " injection = OptionGroup(parser, "Injection", "These options can be "
"used to specify which parameters to test " "used to specify which parameters to test "
"for, provide custom injection payloads and " "for, provide custom injection payloads and "
"optional tampering scripts") "optional tampering scripts")
injection.add_option("-p", dest="testParameter", injection.add_option("-p", dest="testParameter",
help="Testable parameter(s)") help="Testable parameter(s)")
injection.add_option("--dbms", dest="dbms", injection.add_option("--dbms", dest="dbms",
help="Force back-end DBMS to this value") help="Force back-end DBMS to this value")
injection.add_option("--os", dest="os", injection.add_option("--os", dest="os",
help="Force back-end DBMS operating system " help="Force back-end DBMS operating system "
"to this value") "to this value")
injection.add_option("--invalid-bignum", dest="invalidBignum", injection.add_option("--invalid-bignum", dest="invalidBignum",
action="store_true", action="store_true",
help="Use big numbers for invalidating values") help="Use big numbers for invalidating values")
injection.add_option("--invalid-logical", dest="invalidLogical", injection.add_option("--invalid-logical", dest="invalidLogical",
action="store_true", action="store_true",
help="Use logical operations for invalidating values") help="Use logical operations for invalidating values")
injection.add_option("--no-cast", dest="noCast", injection.add_option("--no-cast", dest="noCast",
action="store_true", action="store_true",
help="Turn off payload casting mechanism") help="Turn off payload casting mechanism")
injection.add_option("--no-unescape", dest="noUnescape", injection.add_option("--no-unescape", dest="noUnescape",
action="store_true", action="store_true",
help="Turn off string unescaping mechanism") help="Turn off string unescaping mechanism")
injection.add_option("--prefix", dest="prefix", injection.add_option("--prefix", dest="prefix",
help="Injection payload prefix string") help="Injection payload prefix string")
injection.add_option("--suffix", dest="suffix", injection.add_option("--suffix", dest="suffix",
help="Injection payload suffix string") help="Injection payload suffix string")
injection.add_option("--skip", dest="skip", injection.add_option("--skip", dest="skip",
help="Skip testing for given parameter(s)") help="Skip testing for given parameter(s)")
injection.add_option("--tamper", dest="tamper", injection.add_option("--tamper", dest="tamper",
help="Use given script(s) for tampering injection data") help="Use given script(s) for tampering injection data")
# Detection options # Detection options
detection = OptionGroup(parser, "Detection", "These options can be " detection = OptionGroup(parser, "Detection", "These options can be "
"used to specify how to parse " "used to specify how to parse "
"and compare page content from " "and compare page content from "
"HTTP responses when using blind SQL " "HTTP responses when using blind SQL "
"injection technique") "injection technique")
detection.add_option("--level", dest="level", type="int", detection.add_option("--level", dest="level", type="int",
help="Level of tests to perform (1-5, " help="Level of tests to perform (1-5, "
"default %d)" % defaults.level) "default %d)" % defaults.level)
detection.add_option("--risk", dest="risk", type="int", detection.add_option("--risk", dest="risk", type="int",
help="Risk of tests to perform (0-3, " help="Risk of tests to perform (0-3, "
"default %d)" % defaults.level) "default %d)" % defaults.level)
detection.add_option("--string", dest="string", detection.add_option("--string", dest="string",
help="String to match when " help="String to match when "
"query is evaluated to True") "query is evaluated to True")
detection.add_option("--not-string", dest="notString", detection.add_option("--not-string", dest="notString",
help="String to match when " help="String to match when "
"query is evaluated to False") "query is evaluated to False")
detection.add_option("--regexp", dest="regexp", detection.add_option("--regexp", dest="regexp",
help="Regexp to match when " help="Regexp to match when "
"query is evaluated to True") "query is evaluated to True")
detection.add_option("--code", dest="code", type="int", detection.add_option("--code", dest="code", type="int",
help="HTTP code to match when " help="HTTP code to match when "
"query is evaluated to True") "query is evaluated to True")
detection.add_option("--text-only", dest="textOnly", detection.add_option("--text-only", dest="textOnly",
action="store_true", action="store_true",
help="Compare pages based only on the textual content") help="Compare pages based only on the textual content")
detection.add_option("--titles", dest="titles", detection.add_option("--titles", dest="titles",
action="store_true", action="store_true",
help="Compare pages based only on their titles") help="Compare pages based only on their titles")
# Techniques options # Techniques options
techniques = OptionGroup(parser, "Techniques", "These options can be " techniques = OptionGroup(parser, "Techniques", "These options can be "
"used to tweak testing of specific SQL " "used to tweak testing of specific SQL "
"injection techniques") "injection techniques")
techniques.add_option("--technique", dest="tech", techniques.add_option("--technique", dest="tech",
help="SQL injection techniques to test for " help="SQL injection techniques to test for "
"(default \"%s\")" % defaults.tech) "(default \"%s\")" % defaults.tech)
techniques.add_option("--time-sec", dest="timeSec", techniques.add_option("--time-sec", dest="timeSec",
type="int", type="int",
help="Seconds to delay the DBMS response " help="Seconds to delay the DBMS response "
"(default %d)" % defaults.timeSec) "(default %d)" % defaults.timeSec)
techniques.add_option("--union-cols", dest="uCols", techniques.add_option("--union-cols", dest="uCols",
help="Range of columns to test for UNION query SQL injection") help="Range of columns to test for UNION query SQL injection")
techniques.add_option("--union-char", dest="uChar", techniques.add_option("--union-char", dest="uChar",
help="Character to use for bruteforcing number of columns") help="Character to use for bruteforcing number of columns")
techniques.add_option("--dns-domain", dest="dnsName", techniques.add_option("--dns-domain", dest="dnsName",
help="Domain name used for DNS exfiltration attack") help="Domain name used for DNS exfiltration attack")
techniques.add_option("--second-order", dest="secondOrder", techniques.add_option("--second-order", dest="secondOrder",
help="Resulting page url searched for second-order " help="Resulting page url searched for second-order "
"response") "response")
# Fingerprint options # Fingerprint options
fingerprint = OptionGroup(parser, "Fingerprint") fingerprint = OptionGroup(parser, "Fingerprint")
fingerprint.add_option("-f", "--fingerprint", dest="extensiveFp", fingerprint.add_option("-f", "--fingerprint", dest="extensiveFp",
action="store_true", action="store_true",
help="Perform an extensive DBMS version fingerprint") help="Perform an extensive DBMS version fingerprint")
# Enumeration options # Enumeration options
enumeration = OptionGroup(parser, "Enumeration", "These options can " enumeration = OptionGroup(parser, "Enumeration", "These options can "
"be used to enumerate the back-end database " "be used to enumerate the back-end database "
"management system information, structure " "management system information, structure "
"and data contained in the tables. Moreover " "and data contained in the tables. Moreover "
"you can run your own SQL statements") "you can run your own SQL statements")
enumeration.add_option("-a", "--all", dest="getAll", enumeration.add_option("-a", "--all", dest="getAll",
action="store_true", help="Retrieve everything") action="store_true", help="Retrieve everything")
enumeration.add_option("-b", "--banner", dest="getBanner", enumeration.add_option("-b", "--banner", dest="getBanner",
action="store_true", help="Retrieve DBMS banner") action="store_true", help="Retrieve DBMS banner")
enumeration.add_option("--current-user", dest="getCurrentUser", enumeration.add_option("--current-user", dest="getCurrentUser",
action="store_true", action="store_true",
help="Retrieve DBMS current user") help="Retrieve DBMS current user")
enumeration.add_option("--current-db", dest="getCurrentDb", enumeration.add_option("--current-db", dest="getCurrentDb",
action="store_true", action="store_true",
help="Retrieve DBMS current database") help="Retrieve DBMS current database")
enumeration.add_option("--hostname", dest="getHostname", enumeration.add_option("--hostname", dest="getHostname",
action="store_true", action="store_true",
help="Retrieve DBMS server hostname") help="Retrieve DBMS server hostname")
enumeration.add_option("--is-dba", dest="isDba", enumeration.add_option("--is-dba", dest="isDba",
action="store_true", action="store_true",
help="Detect if the DBMS current user is DBA") help="Detect if the DBMS current user is DBA")
enumeration.add_option("--users", dest="getUsers", action="store_true", enumeration.add_option("--users", dest="getUsers", action="store_true",
help="Enumerate DBMS users") help="Enumerate DBMS users")
enumeration.add_option("--passwords", dest="getPasswordHashes", enumeration.add_option("--passwords", dest="getPasswordHashes",
action="store_true", action="store_true",
help="Enumerate DBMS users password hashes") help="Enumerate DBMS users password hashes")
enumeration.add_option("--privileges", dest="getPrivileges", enumeration.add_option("--privileges", dest="getPrivileges",
action="store_true", action="store_true",
help="Enumerate DBMS users privileges") help="Enumerate DBMS users privileges")
enumeration.add_option("--roles", dest="getRoles", enumeration.add_option("--roles", dest="getRoles",
action="store_true", action="store_true",
help="Enumerate DBMS users roles") help="Enumerate DBMS users roles")
enumeration.add_option("--dbs", dest="getDbs", action="store_true", enumeration.add_option("--dbs", dest="getDbs", action="store_true",
help="Enumerate DBMS databases") help="Enumerate DBMS databases")
enumeration.add_option("--tables", dest="getTables", action="store_true", enumeration.add_option("--tables", dest="getTables", action="store_true",
help="Enumerate DBMS database tables") help="Enumerate DBMS database tables")
enumeration.add_option("--columns", dest="getColumns", action="store_true", enumeration.add_option("--columns", dest="getColumns", action="store_true",
help="Enumerate DBMS database table columns") help="Enumerate DBMS database table columns")
enumeration.add_option("--schema", dest="getSchema", action="store_true", enumeration.add_option("--schema", dest="getSchema", action="store_true",
help="Enumerate DBMS schema") help="Enumerate DBMS schema")
enumeration.add_option("--count", dest="getCount", action="store_true", enumeration.add_option("--count", dest="getCount", action="store_true",
help="Retrieve number of entries for table(s)") help="Retrieve number of entries for table(s)")
enumeration.add_option("--dump", dest="dumpTable", action="store_true", enumeration.add_option("--dump", dest="dumpTable", action="store_true",
help="Dump DBMS database table entries") help="Dump DBMS database table entries")
enumeration.add_option("--dump-all", dest="dumpAll", action="store_true", enumeration.add_option("--dump-all", dest="dumpAll", action="store_true",
help="Dump all DBMS databases tables entries") help="Dump all DBMS databases tables entries")
enumeration.add_option("--search", dest="search", action="store_true", enumeration.add_option("--search", dest="search", action="store_true",
help="Search column(s), table(s) and/or database name(s)") help="Search column(s), table(s) and/or database name(s)")
enumeration.add_option("-D", dest="db", enumeration.add_option("-D", dest="db",
help="DBMS database to enumerate") help="DBMS database to enumerate")
enumeration.add_option("-T", dest="tbl", enumeration.add_option("-T", dest="tbl",
help="DBMS database table to enumerate") help="DBMS database table to enumerate")
enumeration.add_option("-C", dest="col", enumeration.add_option("-C", dest="col",
help="DBMS database table column to enumerate") help="DBMS database table column to enumerate")
enumeration.add_option("-U", dest="user", enumeration.add_option("-U", dest="user",
help="DBMS user to enumerate") help="DBMS user to enumerate")
enumeration.add_option("--exclude-sysdbs", dest="excludeSysDbs", enumeration.add_option("--exclude-sysdbs", dest="excludeSysDbs",
action="store_true", action="store_true",
help="Exclude DBMS system databases when " help="Exclude DBMS system databases when "
"enumerating tables") "enumerating tables")
enumeration.add_option("--start", dest="limitStart", type="int", enumeration.add_option("--start", dest="limitStart", type="int",
help="First query output entry to retrieve") help="First query output entry to retrieve")
enumeration.add_option("--stop", dest="limitStop", type="int", enumeration.add_option("--stop", dest="limitStop", type="int",
help="Last query output entry to retrieve") help="Last query output entry to retrieve")
enumeration.add_option("--first", dest="firstChar", type="int", enumeration.add_option("--first", dest="firstChar", type="int",
help="First query output word character to retrieve") help="First query output word character to retrieve")
enumeration.add_option("--last", dest="lastChar", type="int", enumeration.add_option("--last", dest="lastChar", type="int",
help="Last query output word character to retrieve") help="Last query output word character to retrieve")
enumeration.add_option("--sql-query", dest="query", enumeration.add_option("--sql-query", dest="query",
help="SQL statement to be executed") help="SQL statement to be executed")
enumeration.add_option("--sql-shell", dest="sqlShell", enumeration.add_option("--sql-shell", dest="sqlShell",
action="store_true", action="store_true",
help="Prompt for an interactive SQL shell") help="Prompt for an interactive SQL shell")
enumeration.add_option("--sql-file", dest="sqlFile", enumeration.add_option("--sql-file", dest="sqlFile",
help="Execute SQL statements from given file(s)") help="Execute SQL statements from given file(s)")
# User-defined function options # User-defined function options
brute = OptionGroup(parser, "Brute force", "These " brute = OptionGroup(parser, "Brute force", "These "
"options can be used to run brute force " "options can be used to run brute force "
"checks") "checks")
brute.add_option("--common-tables", dest="commonTables", action="store_true", brute.add_option("--common-tables", dest="commonTables", action="store_true",
help="Check existence of common tables") help="Check existence of common tables")
brute.add_option("--common-columns", dest="commonColumns", action="store_true", brute.add_option("--common-columns", dest="commonColumns", action="store_true",
help="Check existence of common columns") help="Check existence of common columns")
# User-defined function options # User-defined function options
udf = OptionGroup(parser, "User-defined function injection", "These " udf = OptionGroup(parser, "User-defined function injection", "These "
"options can be used to create custom user-defined " "options can be used to create custom user-defined "
"functions") "functions")
udf.add_option("--udf-inject", dest="udfInject", action="store_true", udf.add_option("--udf-inject", dest="udfInject", action="store_true",
help="Inject custom user-defined functions") help="Inject custom user-defined functions")
udf.add_option("--shared-lib", dest="shLib", udf.add_option("--shared-lib", dest="shLib",
help="Local path of the shared library") help="Local path of the shared library")
# File system options # File system options
filesystem = OptionGroup(parser, "File system access", "These options " filesystem = OptionGroup(parser, "File system access", "These options "
"can be used to access the back-end database " "can be used to access the back-end database "
"management system underlying file system") "management system underlying file system")
filesystem.add_option("--file-read", dest="rFile", filesystem.add_option("--file-read", dest="rFile",
help="Read a file from the back-end DBMS " help="Read a file from the back-end DBMS "
"file system") "file system")
filesystem.add_option("--file-write", dest="wFile", filesystem.add_option("--file-write", dest="wFile",
help="Write a local file on the back-end " help="Write a local file on the back-end "
"DBMS file system") "DBMS file system")
filesystem.add_option("--file-dest", dest="dFile", filesystem.add_option("--file-dest", dest="dFile",
help="Back-end DBMS absolute filepath to " help="Back-end DBMS absolute filepath to "
"write to") "write to")
# Takeover options # Takeover options
takeover = OptionGroup(parser, "Operating system access", "These " takeover = OptionGroup(parser, "Operating system access", "These "
"options can be used to access the back-end " "options can be used to access the back-end "
"database management system underlying " "database management system underlying "
"operating system") "operating system")
takeover.add_option("--os-cmd", dest="osCmd", takeover.add_option("--os-cmd", dest="osCmd",
help="Execute an operating system command") help="Execute an operating system command")
takeover.add_option("--os-shell", dest="osShell", takeover.add_option("--os-shell", dest="osShell",
action="store_true", action="store_true",
help="Prompt for an interactive operating " help="Prompt for an interactive operating "
"system shell") "system shell")
takeover.add_option("--os-pwn", dest="osPwn", takeover.add_option("--os-pwn", dest="osPwn",
action="store_true", action="store_true",
help="Prompt for an out-of-band shell, " help="Prompt for an out-of-band shell, "
"meterpreter or VNC") "meterpreter or VNC")
takeover.add_option("--os-smbrelay", dest="osSmb", takeover.add_option("--os-smbrelay", dest="osSmb",
action="store_true", action="store_true",
help="One click prompt for an OOB shell, " help="One click prompt for an OOB shell, "
"meterpreter or VNC") "meterpreter or VNC")
takeover.add_option("--os-bof", dest="osBof", takeover.add_option("--os-bof", dest="osBof",
action="store_true", action="store_true",
help="Stored procedure buffer overflow " help="Stored procedure buffer overflow "
"exploitation") "exploitation")
takeover.add_option("--priv-esc", dest="privEsc", takeover.add_option("--priv-esc", dest="privEsc",
action="store_true", action="store_true",
help="Database process' user privilege escalation") help="Database process' user privilege escalation")
takeover.add_option("--msf-path", dest="msfPath", takeover.add_option("--msf-path", dest="msfPath",
help="Local path where Metasploit Framework " help="Local path where Metasploit Framework "
"is installed") "is installed")
takeover.add_option("--tmp-path", dest="tmpPath", takeover.add_option("--tmp-path", dest="tmpPath",
help="Remote absolute path of temporary files " help="Remote absolute path of temporary files "
"directory") "directory")
# Windows registry options # Windows registry options
windows = OptionGroup(parser, "Windows registry access", "These " windows = OptionGroup(parser, "Windows registry access", "These "
"options can be used to access the back-end " "options can be used to access the back-end "
"database management system Windows " "database management system Windows "
"registry") "registry")
windows.add_option("--reg-read", dest="regRead", windows.add_option("--reg-read", dest="regRead",
action="store_true", action="store_true",
help="Read a Windows registry key value") help="Read a Windows registry key value")
windows.add_option("--reg-add", dest="regAdd", windows.add_option("--reg-add", dest="regAdd",
action="store_true", action="store_true",
help="Write a Windows registry key value data") help="Write a Windows registry key value data")
windows.add_option("--reg-del", dest="regDel", windows.add_option("--reg-del", dest="regDel",
action="store_true", action="store_true",
help="Delete a Windows registry key value") help="Delete a Windows registry key value")
windows.add_option("--reg-key", dest="regKey", windows.add_option("--reg-key", dest="regKey",
help="Windows registry key") help="Windows registry key")
windows.add_option("--reg-value", dest="regVal", windows.add_option("--reg-value", dest="regVal",
help="Windows registry key value") help="Windows registry key value")
windows.add_option("--reg-data", dest="regData", windows.add_option("--reg-data", dest="regData",
help="Windows registry key value data") help="Windows registry key value data")
windows.add_option("--reg-type", dest="regType", windows.add_option("--reg-type", dest="regType",
help="Windows registry key value type") help="Windows registry key value type")
# General options # General options
general = OptionGroup(parser, "General", "These options can be used " general = OptionGroup(parser, "General", "These options can be used "
"to set some general working parameters" ) "to set some general working parameters")
#general.add_option("-x", dest="xmlFile", #general.add_option("-x", dest="xmlFile",
# help="Dump the data into an XML file") # help="Dump the data into an XML file")
general.add_option("-t", dest="trafficFile", general.add_option("-t", dest="trafficFile",
help="Log all HTTP traffic into a " help="Log all HTTP traffic into a "
"textual file") "textual file")
general.add_option("--batch", dest="batch", general.add_option("--batch", dest="batch",
action="store_true", action="store_true",
help="Never ask for user input, use the default behaviour") help="Never ask for user input, use the default behaviour")
general.add_option("--charset", dest="charset", general.add_option("--charset", dest="charset",
help="Force character encoding used for data retrieval") help="Force character encoding used for data retrieval")
general.add_option("--check-tor", dest="checkTor", general.add_option("--check-tor", dest="checkTor",
action="store_true", action="store_true",
help="Check to see if Tor is used properly") help="Check to see if Tor is used properly")
general.add_option("--crawl", dest="crawlDepth", type="int", general.add_option("--crawl", dest="crawlDepth", type="int",
help="Crawl the website starting from the target url") help="Crawl the website starting from the target url")
general.add_option("--csv-del", dest="csvDel", general.add_option("--csv-del", dest="csvDel",
help="Delimiting character used in CSV output " help="Delimiting character used in CSV output "
"(default \"%s\")" % defaults.csvDel) "(default \"%s\")" % defaults.csvDel)
general.add_option("--dbms-cred", dest="dbmsCred", general.add_option("--dbms-cred", dest="dbmsCred",
help="DBMS authentication credentials (user:password)") help="DBMS authentication credentials (user:password)")
general.add_option("--dump-format", dest="dumpFormat", general.add_option("--dump-format", dest="dumpFormat",
help="Format of dumped data (CSV (default), HTML or SQLITE)") help="Format of dumped data (CSV (default), HTML or SQLITE)")
general.add_option("--eta", dest="eta", general.add_option("--eta", dest="eta",
action="store_true", action="store_true",
help="Display for each output the " help="Display for each output the "
"estimated time of arrival") "estimated time of arrival")
general.add_option("--flush-session", dest="flushSession", general.add_option("--flush-session", dest="flushSession",
action="store_true", action="store_true",
help="Flush session files for current target") help="Flush session files for current target")
general.add_option("--forms", dest="forms", general.add_option("--forms", dest="forms",
action="store_true", action="store_true",
help="Parse and test forms on target url") help="Parse and test forms on target url")
general.add_option("--fresh-queries", dest="freshQueries", general.add_option("--fresh-queries", dest="freshQueries",
action="store_true", action="store_true",
help="Ignores query results stored in session file") help="Ignores query results stored in session file")
general.add_option("--hex", dest="hexConvert", general.add_option("--hex", dest="hexConvert",
action="store_true", action="store_true",
help="Uses DBMS hex function(s) for data retrieval") help="Uses DBMS hex function(s) for data retrieval")
general.add_option("--output-dir", dest="oDir", general.add_option("--output-dir", dest="oDir",
action="store", action="store",
help="Custom output directory path") help="Custom output directory path")
general.add_option("--parse-errors", dest="parseErrors", general.add_option("--parse-errors", dest="parseErrors",
action="store_true", action="store_true",
help="Parse and display DBMS error messages from responses") help="Parse and display DBMS error messages from responses")
general.add_option("--save", dest="saveCmdline", general.add_option("--save", dest="saveCmdline",
action="store_true", action="store_true",
help="Save options to a configuration INI file") help="Save options to a configuration INI file")
general.add_option("--tor", dest="tor", general.add_option("--tor", dest="tor",
action="store_true", action="store_true",
help="Use Tor anonymity network") help="Use Tor anonymity network")
general.add_option("--tor-port", dest="torPort", general.add_option("--tor-port", dest="torPort",
help="Set Tor proxy port other than default") help="Set Tor proxy port other than default")
general.add_option("--tor-type", dest="torType", general.add_option("--tor-type", dest="torType",
help="Set Tor proxy type (HTTP (default), SOCKS4 or SOCKS5)") help="Set Tor proxy type (HTTP (default), SOCKS4 or SOCKS5)")
general.add_option("--update", dest="updateAll", general.add_option("--update", dest="updateAll",
action="store_true", action="store_true",
help="Update sqlmap") help="Update sqlmap")
# Miscellaneous options # Miscellaneous options
miscellaneous = OptionGroup(parser, "Miscellaneous") miscellaneous = OptionGroup(parser, "Miscellaneous")
miscellaneous.add_option("-z", dest="mnemonics", miscellaneous.add_option("-z", dest="mnemonics",
help="Use short mnemonics (e.g. \"flu,bat,ban,tec=EU\")") help="Use short mnemonics (e.g. \"flu,bat,ban,tec=EU\")")
miscellaneous.add_option("--answers", dest="answers", miscellaneous.add_option("--answers", dest="answers",
help="Set question answers (e.g. \"quit=N,follow=N\")") help="Set question answers (e.g. \"quit=N,follow=N\")")
miscellaneous.add_option("--check-payload", dest="checkPayload", miscellaneous.add_option("--check-payload", dest="checkPayload",
action="store_true", action="store_true",
help="Offline WAF/IPS/IDS payload detection testing") help="Offline WAF/IPS/IDS payload detection testing")
miscellaneous.add_option("--check-waf", dest="checkWaf", miscellaneous.add_option("--check-waf", dest="checkWaf",
action="store_true", action="store_true",
help="Check for existence of WAF/IPS/IDS protection") help="Check for existence of WAF/IPS/IDS protection")
miscellaneous.add_option("--cleanup", dest="cleanup", miscellaneous.add_option("--cleanup", dest="cleanup",
action="store_true", action="store_true",
help="Clean up the DBMS by sqlmap specific " help="Clean up the DBMS by sqlmap specific "
"UDF and tables") "UDF and tables")
miscellaneous.add_option("--dependencies", dest="dependencies", miscellaneous.add_option("--dependencies", dest="dependencies",
action="store_true", action="store_true",
help="Check for missing (non-core) sqlmap dependencies") help="Check for missing (non-core) sqlmap dependencies")
miscellaneous.add_option("--disable-coloring", dest="disableColoring", miscellaneous.add_option("--disable-coloring", dest="disableColoring",
action="store_true", action="store_true",
help="Disable console output coloring") help="Disable console output coloring")
miscellaneous.add_option("--gpage", dest="googlePage", type="int", miscellaneous.add_option("--gpage", dest="googlePage", type="int",
help="Use Google dork results from specified page number") help="Use Google dork results from specified page number")
miscellaneous.add_option("--mobile", dest="mobile", miscellaneous.add_option("--mobile", dest="mobile",
action="store_true", action="store_true",
help="Imitate smartphone through HTTP User-Agent header") help="Imitate smartphone through HTTP User-Agent header")
miscellaneous.add_option("--page-rank", dest="pageRank", miscellaneous.add_option("--page-rank", dest="pageRank",
action="store_true", action="store_true",
help="Display page rank (PR) for Google dork results") help="Display page rank (PR) for Google dork results")
miscellaneous.add_option("--purge-output", dest="purgeOutput", miscellaneous.add_option("--purge-output", dest="purgeOutput",
action="store_true", action="store_true",
help="Safely remove all content from output directory") help="Safely remove all content from output directory")
miscellaneous.add_option("--smart", dest="smart", miscellaneous.add_option("--smart", dest="smart",
action="store_true", action="store_true",
help="Conduct through tests only if positive heuristic(s)") help="Conduct through tests only if positive heuristic(s)")
miscellaneous.add_option("--test-filter", dest="testFilter", miscellaneous.add_option("--test-filter", dest="testFilter",
help="Select tests by payloads and/or titles (e.g. ROW)") help="Select tests by payloads and/or titles (e.g. ROW)")
miscellaneous.add_option("--wizard", dest="wizard", miscellaneous.add_option("--wizard", dest="wizard",
action="store_true", action="store_true",
help="Simple wizard interface for beginner users") help="Simple wizard interface for beginner users")
# Hidden and/or experimental options # Hidden and/or experimental options
parser.add_option("--beep", dest="beep", action="store_true", parser.add_option("--beep", dest="beep", action="store_true",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option("--profile", dest="profile", action="store_true", parser.add_option("--profile", dest="profile", action="store_true",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option("--cpu-throttle", dest="cpuThrottle", type="int", parser.add_option("--cpu-throttle", dest="cpuThrottle", type="int",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option("--force-dns", dest="forceDns", action="store_true", parser.add_option("--force-dns", dest="forceDns", action="store_true",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option("--smoke-test", dest="smokeTest", action="store_true", parser.add_option("--smoke-test", dest="smokeTest", action="store_true",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option("--live-test", dest="liveTest", action="store_true", parser.add_option("--live-test", dest="liveTest", action="store_true",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option("--run-case", dest="runCase", type="int", parser.add_option("--run-case", dest="runCase", type="int",
help=SUPPRESS_HELP) help=SUPPRESS_HELP)
parser.add_option_group(target) parser.add_option_group(target)
parser.add_option_group(request) parser.add_option_group(request)
@ -745,10 +737,11 @@ def cmdLineParser():
# Expand given mnemonic options (e.g. -z "ign,flu,bat") # Expand given mnemonic options (e.g. -z "ign,flu,bat")
for i in xrange(len(sys.argv) - 1): for i in xrange(len(sys.argv) - 1):
if sys.argv[i] == '-z': if sys.argv[i] == '-z':
expandMnemonics(sys.argv[i+1], parser, args) expandMnemonics(sys.argv[i + 1], parser, args)
if not any((args.direct, args.url, args.logFile, args.bulkFile, args.googleDork, args.configFile, \ if not any((args.direct, args.url, args.logFile, args.bulkFile, args.googleDork, args.configFile,\
args.requestFile, args.updateAll, args.smokeTest, args.liveTest, args.wizard, args.dependencies, args.purgeOutput)): args.requestFile, args.updateAll, args.smokeTest, args.liveTest, args.wizard, args.dependencies,
args.purgeOutput)):
errMsg = "missing a mandatory option (-d, -u, -l, -m, -r, -g, -c, --wizard, --update, --purge-output or --dependencies), " errMsg = "missing a mandatory option (-d, -u, -l, -m, -r, -g, -c, --wizard, --update, --purge-output or --dependencies), "
errMsg += "use -h for basic or -hh for advanced help" errMsg += "use -h for basic or -hh for advanced help"
parser.error(errMsg) parser.error(errMsg)

View File

@ -6,16 +6,11 @@ See the file 'doc/COPYING' for copying permission
""" """
import codecs import codecs
from ConfigParser import MissingSectionHeaderError from ConfigParser import MissingSectionHeaderError
from lib.core.common import checkFile from lib.core.common import checkFile, unArrayizeValue, UnicodeRawConfigParser
from lib.core.common import unArrayizeValue from lib.core.data import conf, logger
from lib.core.common import UnicodeRawConfigParser from lib.core.exception import sqlmapMissingMandatoryOptionException, sqlmapSyntaxException
from lib.core.data import conf
from lib.core.data import logger
from lib.core.exception import sqlmapMissingMandatoryOptionException
from lib.core.exception import sqlmapSyntaxException
from lib.core.optiondict import optDict from lib.core.optiondict import optDict
from lib.core.settings import UNICODE_ENCODING from lib.core.settings import UNICODE_ENCODING

View File

@ -24,13 +24,13 @@ def headersParser(headers):
if not kb.headerPaths: if not kb.headerPaths:
kb.headerPaths = { kb.headerPaths = {
"cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"), "cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"),
"microsoftsharepointteamservices": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "sharepoint.xml"), "microsoftsharepointteamservices": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "sharepoint.xml"),
"server": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "server.xml"), "server": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "server.xml"),
"servlet-engine": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "servlet.xml"), "servlet-engine": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "servlet.xml"),
"set-cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"), "set-cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"),
"x-aspnet-version": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-aspnet-version.xml"), "x-aspnet-version": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-aspnet-version.xml"),
"x-powered-by": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-powered-by.xml") "x-powered-by": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-powered-by.xml")
} }
for header in itertools.ifilter(lambda x: x in kb.headerPaths, headers): for header in itertools.ifilter(lambda x: x in kb.headerPaths, headers):

View File

@ -42,6 +42,7 @@ class htmlHandler(ContentHandler):
self.dbms = self._dbms self.dbms = self._dbms
self._markAsErrorPage() self._markAsErrorPage()
def htmlParser(page): def htmlParser(page):
""" """
This function calls a class that parses the input HTML page to This function calls a class that parses the input HTML page to

View File

@ -7,8 +7,7 @@ See the file 'doc/COPYING' for copying permission
from xml.etree import ElementTree as et from xml.etree import ElementTree as et
from lib.core.data import conf from lib.core.data import conf, paths
from lib.core.data import paths
from lib.core.datatype import AttribDict from lib.core.datatype import AttribDict
def cleanupVals(text, tag): def cleanupVals(text, tag):
@ -38,6 +37,7 @@ def cleanupVals(text, tag):
return text return text
def parseXmlNode(node): def parseXmlNode(node):
for element in node.getiterator('boundary'): for element in node.getiterator('boundary'):
boundary = AttribDict() boundary = AttribDict()
@ -74,6 +74,7 @@ def parseXmlNode(node):
conf.tests.append(test) conf.tests.append(test)
def loadPayloads(): def loadPayloads():
doc = et.parse(paths.PAYLOADS_XML) doc = et.parse(paths.PAYLOADS_XML)
root = doc.getroot() root = doc.getroot()

View File

@ -4,5 +4,3 @@
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -9,9 +9,12 @@ import codecs
import gzip import gzip
import logging import logging
import re import re
import StringIO
import struct import struct
import zlib import zlib
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from lib.core.common import extractErrorMessage from lib.core.common import extractErrorMessage
from lib.core.common import extractRegexResult from lib.core.common import extractRegexResult
@ -46,14 +49,14 @@ def forgeHeaders(items=None):
items = items or {} items = items or {}
for _ in items.keys(): for _ in items.iterkeys():
if items[_] is None: if items[_] is None:
del items[_] del items[_]
headers = dict(conf.httpHeaders) headers = dict(conf.httpHeaders)
headers.update(items or {}) headers.update(items or {})
headers = dict(("-".join(_.capitalize() for _ in key.split('-')), value) for (key, value) in headers.items()) headers = dict(("-".join(_.capitalize() for _ in key.split('-')), value) for (key, value) in headers.iteritems())
if conf.cj: if conf.cj:
if HTTPHEADER.COOKIE in headers: if HTTPHEADER.COOKIE in headers:

View File

@ -4,6 +4,7 @@
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
#TODO: Move to requests
import urllib2 import urllib2
@ -12,6 +13,7 @@ class SmartHTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
Reference: http://selenic.com/hg/rev/6c51a5056020 Reference: http://selenic.com/hg/rev/6c51a5056020
Fix for a: http://bugs.python.org/issue8797 Fix for a: http://bugs.python.org/issue8797
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs) urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)
self.retried_req = set() self.retried_req = set()
@ -29,11 +31,11 @@ class SmartHTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
self.retried_req.add(hash(req)) self.retried_req.add(hash(req))
self.retried_count = 0 self.retried_count = 0
else: else:
if self.retried_count > 5: if self.retried_count > 5:
raise urllib2.HTTPError(req.get_full_url(), 401, "basic auth failed", raise urllib2.HTTPError(req.get_full_url(), 401, "basic auth failed",
headers, None) headers, None)
else: else:
self.retried_count += 1 self.retried_count += 1
return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed( return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(
self, auth_header, host, req, headers) self, auth_header, host, req, headers)

View File

@ -5,6 +5,8 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
#TODO: Move to requests
import httplib import httplib
import urllib2 import urllib2
import sys import sys

View File

@ -7,29 +7,17 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.common import extractRegexResult from lib.core.common import extractRegexResult, getFilteredPageContent, listToStrValue, removeDynamicContent, \
from lib.core.common import getFilteredPageContent wasLastRequestDBMSError, wasLastRequestHTTPError
from lib.core.common import listToStrValue from lib.core.data import conf, kb, logger
from lib.core.common import removeDynamicContent
from lib.core.common import wasLastRequestDBMSError
from lib.core.common import wasLastRequestHTTPError
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.exception import sqlmapNoneDataException from lib.core.exception import sqlmapNoneDataException
from lib.core.settings import DEFAULT_PAGE_ENCODING from lib.core.settings import DEFAULT_PAGE_ENCODING, DIFF_TOLERANCE, HTML_TITLE_REGEX, MIN_RATIO, MAX_RATIO, \
from lib.core.settings import DIFF_TOLERANCE REFLECTED_VALUE_MARKER, LOWER_RATIO_BOUND, UPPER_RATIO_BOUND
from lib.core.settings import HTML_TITLE_REGEX
from lib.core.settings import MIN_RATIO
from lib.core.settings import MAX_RATIO
from lib.core.settings import REFLECTED_VALUE_MARKER
from lib.core.settings import LOWER_RATIO_BOUND
from lib.core.settings import UPPER_RATIO_BOUND
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
def comparison(page, headers, code=None, getRatioValue=False, pageLength=None): def comparison(page, headers, code=None, getRatioValue=False, pageLength=None):
_ = _adjust(_comparison(page, headers, code, getRatioValue, pageLength), getRatioValue) return _adjust(_comparison(page, headers, code, getRatioValue, pageLength), getRatioValue)
return _
def _adjust(condition, getRatioValue): def _adjust(condition, getRatioValue):
if not any((conf.string, conf.notString, conf.regexp, conf.code)): if not any((conf.string, conf.notString, conf.regexp, conf.code)):

View File

@ -17,62 +17,21 @@ import traceback
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import asciifyUrl from lib.core.common import asciifyUrl, calculateDeltaSeconds, clearConsoleLine, cpuThrottle, evaluateCode,\
from lib.core.common import calculateDeltaSeconds extractRegexResult, findMultipartPostBoundary, getCurrentThreadData, getHostHeader, getRequestHeader,\
from lib.core.common import clearConsoleLine getUnicode, logHTTPTraffic, randomizeParameterValue, readInput, removeReflectiveValues, singleTimeWarnMessage,\
from lib.core.common import cpuThrottle stdev, wasLastRequestDelayed, unicodeencode, urlencode
from lib.core.common import evaluateCode from lib.core.data import conf, kb, logger
from lib.core.common import extractRegexResult
from lib.core.common import findMultipartPostBoundary
from lib.core.common import getCurrentThreadData
from lib.core.common import getHostHeader
from lib.core.common import getRequestHeader
from lib.core.common import getUnicode
from lib.core.common import logHTTPTraffic
from lib.core.common import randomizeParameterValue
from lib.core.common import readInput
from lib.core.common import removeReflectiveValues
from lib.core.common import singleTimeWarnMessage
from lib.core.common import stdev
from lib.core.common import wasLastRequestDelayed
from lib.core.common import unicodeencode
from lib.core.common import urlencode
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.dicts import POST_HINT_CONTENT_TYPES from lib.core.dicts import POST_HINT_CONTENT_TYPES
from lib.core.enums import ADJUST_TIME_DELAY from lib.core.enums import ADJUST_TIME_DELAY, CUSTOM_LOGGING, HTTPHEADER, HTTPMETHOD, NULLCONNECTION, PAYLOAD,\
from lib.core.enums import CUSTOM_LOGGING PLACE, POST_HINT, REDIRECTION
from lib.core.enums import HTTPHEADER from lib.core.exception import sqlmapCompressionException, sqlmapConnectionException, sqlmapSyntaxException,\
from lib.core.enums import HTTPMETHOD sqlmapValueException
from lib.core.enums import NULLCONNECTION from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR, DEFAULT_CONTENT_TYPE, HTTP_ACCEPT_HEADER_VALUE,\
from lib.core.enums import PAYLOAD HTTP_ACCEPT_ENCODING_HEADER_VALUE, HTTP_SILENT_TIMEOUT, MAX_CONNECTION_CHUNK_SIZE, MAX_CONNECTIONS_REGEX,\
from lib.core.enums import PLACE MAX_CONNECTION_TOTAL_SIZE, META_REFRESH_REGEX, MIN_TIME_RESPONSES, IS_WIN, LARGE_CHUNK_TRIM_MARKER,\
from lib.core.enums import POST_HINT PERMISSION_DENIED_REGEX, UNENCODED_ORIGINAL_VALUE, URI_HTTP_HEADER, WARN_TIME_STDEV
from lib.core.enums import REDIRECTION from lib.request.basic import decodePage, forgeHeaders, processResponse
from lib.core.exception import sqlmapCompressionException
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapValueException
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
from lib.core.settings import DEFAULT_CONTENT_TYPE
from lib.core.settings import HTTP_ACCEPT_HEADER_VALUE
from lib.core.settings import HTTP_ACCEPT_ENCODING_HEADER_VALUE
from lib.core.settings import HTTP_SILENT_TIMEOUT
from lib.core.settings import MAX_CONNECTION_CHUNK_SIZE
from lib.core.settings import MAX_CONNECTIONS_REGEX
from lib.core.settings import MAX_CONNECTION_TOTAL_SIZE
from lib.core.settings import META_REFRESH_REGEX
from lib.core.settings import MIN_TIME_RESPONSES
from lib.core.settings import IS_WIN
from lib.core.settings import LARGE_CHUNK_TRIM_MARKER
from lib.core.settings import PERMISSION_DENIED_REGEX
from lib.core.settings import UNENCODED_ORIGINAL_VALUE
from lib.core.settings import URI_HTTP_HEADER
from lib.core.settings import WARN_TIME_STDEV
from lib.request.basic import decodePage
from lib.request.basic import forgeHeaders
from lib.request.basic import processResponse
from lib.request.direct import direct from lib.request.direct import direct
from lib.request.comparison import comparison from lib.request.comparison import comparison
from lib.request.methodrequest import MethodRequest from lib.request.methodrequest import MethodRequest
@ -138,7 +97,7 @@ class Connect:
if not kb.dnsMode and conn: if not kb.dnsMode and conn:
headers = conn.info() headers = conn.info()
if headers and (headers.getheader(HTTPHEADER.CONTENT_ENCODING, "").lower() in ("gzip", "deflate")\ if headers and (headers.getheader(HTTPHEADER.CONTENT_ENCODING, "").lower() in ("gzip", "deflate")\
or "text" not in headers.getheader(HTTPHEADER.CONTENT_TYPE, "").lower()): or "text" not in headers.getheader(HTTPHEADER.CONTENT_TYPE, "").lower()):
retVal = conn.read() retVal = conn.read()
else: else:
while True: while True:
@ -146,7 +105,8 @@ class Connect:
if len(_) == MAX_CONNECTION_CHUNK_SIZE: if len(_) == MAX_CONNECTION_CHUNK_SIZE:
warnMsg = "large response detected. This could take a while" warnMsg = "large response detected. This could take a while"
singleTimeWarnMessage(warnMsg) singleTimeWarnMessage(warnMsg)
_ = re.sub(r"(?si)%s.+?%s" % (kb.chars.stop, kb.chars.start), "%s%s%s" % (kb.chars.stop, LARGE_CHUNK_TRIM_MARKER, kb.chars.start), _) _ = re.sub(r"(?si)%s.+?%s" % (kb.chars.stop, kb.chars.start),
"%s%s%s" % (kb.chars.stop, LARGE_CHUNK_TRIM_MARKER, kb.chars.start), _)
retVal += _ retVal += _
else: else:
retVal += _ retVal += _
@ -174,30 +134,31 @@ class Connect:
threadData = getCurrentThreadData() threadData = getCurrentThreadData()
threadData.lastRequestUID += 1 threadData.lastRequestUID += 1
url = kwargs.get('url', conf.url) url = kwargs.get('url', conf.url)
get = kwargs.get('get', None) get = kwargs.get('get', None)
post = kwargs.get('post', None) post = kwargs.get('post', None)
method = kwargs.get('method', None) method = kwargs.get('method', None)
cookie = kwargs.get('cookie', None) cookie = kwargs.get('cookie', None)
ua = kwargs.get('ua', None) ua = kwargs.get('ua', None)
referer = kwargs.get('referer', None) referer = kwargs.get('referer', None)
host = kwargs.get('host', conf.host) host = kwargs.get('host', conf.host)
direct = kwargs.get('direct', False) direct = kwargs.get('direct', False)
multipart = kwargs.get('multipart', False) multipart = kwargs.get('multipart', False)
silent = kwargs.get('silent', False) silent = kwargs.get('silent', False)
raise404 = kwargs.get('raise404', True) raise404 = kwargs.get('raise404', True)
auxHeaders = kwargs.get('auxHeaders', None) auxHeaders = kwargs.get('auxHeaders', None)
response = kwargs.get('response', False) response = kwargs.get('response', False)
ignoreTimeout = kwargs.get('ignoreTimeout', kb.ignoreTimeout) ignoreTimeout = kwargs.get('ignoreTimeout', kb.ignoreTimeout)
refreshing = kwargs.get('refreshing', False) refreshing = kwargs.get('refreshing', False)
retrying = kwargs.get('retrying', False) retrying = kwargs.get('retrying', False)
crawling = kwargs.get('crawling', False) crawling = kwargs.get('crawling', False)
if not urlparse.urlsplit(url).netloc: if not urlparse.urlsplit(url).netloc:
url = urlparse.urljoin(conf.url, url) url = urlparse.urljoin(conf.url, url)
# flag to know if we are dealing with the same target host # flag to know if we are dealing with the same target host
target = reduce(lambda x, y: x == y, map(lambda x: urlparse.urlparse(x).netloc.split(':')[0], [url, conf.url or ""])) target = reduce(lambda x, y: x == y,
map(lambda x: urlparse.urlparse(x).netloc.split(':')[0], [url, conf.url or ""]))
if not retrying: if not retrying:
# Reset the number of connection retries # Reset the number of connection retries
@ -211,8 +172,10 @@ class Connect:
page = None page = None
_ = urlparse.urlsplit(url) _ = urlparse.urlsplit(url)
requestMsg = u"HTTP request [#%d]:\n%s " % (threadData.lastRequestUID, method or (HTTPMETHOD.POST if post is not None else HTTPMETHOD.GET)) requestMsg = u"HTTP request [#%d]:\n%s " % (
requestMsg += ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) if not any((refreshing, crawling)) else url threadData.lastRequestUID, method or (HTTPMETHOD.POST if post is not None else HTTPMETHOD.GET))
requestMsg += ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) if not any(
(refreshing, crawling)) else url
responseMsg = u"HTTP response " responseMsg = u"HTTP response "
requestHeaders = u"" requestHeaders = u""
responseHeaders = None responseHeaders = None
@ -252,7 +215,8 @@ class Connect:
page = Connect.__connReadProxy(conn) page = Connect.__connReadProxy(conn)
responseHeaders = conn.info() responseHeaders = conn.info()
responseHeaders[URI_HTTP_HEADER] = conn.geturl() responseHeaders[URI_HTTP_HEADER] = conn.geturl()
page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING), responseHeaders.get(HTTPHEADER.CONTENT_TYPE)) page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING),
responseHeaders.get(HTTPHEADER.CONTENT_TYPE))
return page return page
@ -289,7 +253,8 @@ class Connect:
headers[HTTPHEADER.PROXY_AUTHORIZATION] = kb.proxyAuthHeader headers[HTTPHEADER.PROXY_AUTHORIZATION] = kb.proxyAuthHeader
headers[HTTPHEADER.ACCEPT] = HTTP_ACCEPT_HEADER_VALUE headers[HTTPHEADER.ACCEPT] = HTTP_ACCEPT_HEADER_VALUE
headers[HTTPHEADER.ACCEPT_ENCODING] = HTTP_ACCEPT_ENCODING_HEADER_VALUE if method != HTTPMETHOD.HEAD and kb.pageCompress else "identity" headers[
HTTPHEADER.ACCEPT_ENCODING] = HTTP_ACCEPT_ENCODING_HEADER_VALUE if method != HTTPMETHOD.HEAD and kb.pageCompress else "identity"
headers[HTTPHEADER.HOST] = host or getHostHeader(url) headers[HTTPHEADER.HOST] = host or getHostHeader(url)
if post is not None and HTTPHEADER.CONTENT_TYPE not in headers: if post is not None and HTTPHEADER.CONTENT_TYPE not in headers:
@ -320,12 +285,15 @@ class Connect:
else: else:
req = urllib2.Request(url, post, headers) req = urllib2.Request(url, post, headers)
requestHeaders += "\n".join("%s: %s" % (key.capitalize() if isinstance(key, basestring) else key, getUnicode(value)) for (key, value) in req.header_items()) requestHeaders += "\n".join(
"%s: %s" % (key.capitalize() if isinstance(key, basestring) else key, getUnicode(value)) for (
key, value) in req.header_items())
if not getRequestHeader(req, HTTPHEADER.COOKIE) and conf.cj: if not getRequestHeader(req, HTTPHEADER.COOKIE) and conf.cj:
conf.cj._policy._now = conf.cj._now = int(time.time()) conf.cj._policy._now = conf.cj._now = int(time.time())
cookies = conf.cj._cookies_for_request(req) cookies = conf.cj._cookies_for_request(req)
requestHeaders += "\n%s" % ("Cookie: %s" % ";".join("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value)) for cookie in cookies)) requestHeaders += "\n%s" % ("Cookie: %s" % ";".join(
"%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value)) for cookie in cookies))
if post is not None: if post is not None:
if not getRequestHeader(req, HTTPHEADER.CONTENT_LENGTH): if not getRequestHeader(req, HTTPHEADER.CONTENT_LENGTH):
@ -360,7 +328,7 @@ class Connect:
# Get HTTP response # Get HTTP response
if hasattr(conn, 'redurl'): if hasattr(conn, 'redurl'):
page = threadData.lastRedirectMsg[1] if kb.redirectChoice == REDIRECTION.NO\ page = threadData.lastRedirectMsg[1] if kb.redirectChoice == REDIRECTION.NO\
else Connect.__connReadProxy(conn) else Connect.__connReadProxy(conn)
skipLogTraffic = kb.redirectChoice == REDIRECTION.NO skipLogTraffic = kb.redirectChoice == REDIRECTION.NO
code = conn.redcode code = conn.redcode
else: else:
@ -369,7 +337,8 @@ class Connect:
code = code or conn.code code = code or conn.code
responseHeaders = conn.info() responseHeaders = conn.info()
responseHeaders[URI_HTTP_HEADER] = conn.geturl() responseHeaders[URI_HTTP_HEADER] = conn.geturl()
page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING), responseHeaders.get(HTTPHEADER.CONTENT_TYPE)) page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING),
responseHeaders.get(HTTPHEADER.CONTENT_TYPE))
status = getUnicode(conn.msg) status = getUnicode(conn.msg)
if extractRegexResult(META_REFRESH_REGEX, page) and not refreshing: if extractRegexResult(META_REFRESH_REGEX, page) and not refreshing:
@ -391,7 +360,7 @@ class Connect:
if url.lower().startswith('http://'): if url.lower().startswith('http://'):
kwargs['url'] = url kwargs['url'] = url
else: else:
kwargs['url'] = conf.url[:conf.url.rfind('/')+1] + url kwargs['url'] = conf.url[:conf.url.rfind('/') + 1] + url
threadData.lastRedirectMsg = (threadData.lastRequestUID, page) threadData.lastRedirectMsg = (threadData.lastRequestUID, page)
kwargs['refreshing'] = True kwargs['refreshing'] = True
@ -421,7 +390,8 @@ class Connect:
page = e.read() page = e.read()
responseHeaders = e.info() responseHeaders = e.info()
responseHeaders[URI_HTTP_HEADER] = e.geturl() responseHeaders[URI_HTTP_HEADER] = e.geturl()
page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING), responseHeaders.get(HTTPHEADER.CONTENT_TYPE)) page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING),
responseHeaders.get(HTTPHEADER.CONTENT_TYPE))
except socket.timeout: except socket.timeout:
warnMsg = "connection timed out while trying " warnMsg = "connection timed out while trying "
warnMsg += "to get error page information (%d)" % e.code warnMsg += "to get error page information (%d)" % e.code
@ -443,9 +413,12 @@ class Connect:
responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, status) responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, status)
if responseHeaders: if responseHeaders:
logHeaders = "\n".join("%s: %s" % (key.capitalize() if isinstance(key, basestring) else key, getUnicode(value)) for (key, value) in responseHeaders.items()) logHeaders = "\n".join(
"%s: %s" % (key.capitalize() if isinstance(key, basestring) else key, getUnicode(value)) for (
key, value) in responseHeaders.items())
logHTTPTraffic(requestMsg, "%s%s\n\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE])) logHTTPTraffic(requestMsg,
"%s%s\n\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]))
skipLogTraffic = True skipLogTraffic = True
@ -486,7 +459,9 @@ class Connect:
debugMsg = "got HTTP error code: %d (%s)" % (code, status) debugMsg = "got HTTP error code: %d (%s)" % (code, status)
logger.debug(debugMsg) logger.debug(debugMsg)
except (urllib2.URLError, socket.error, socket.timeout, httplib.BadStatusLine, httplib.IncompleteRead, ProxyError, sqlmapCompressionException), e: except (
urllib2.URLError, socket.error, socket.timeout, httplib.BadStatusLine, httplib.IncompleteRead, ProxyError,
sqlmapCompressionException), e:
tbMsg = traceback.format_exc() tbMsg = traceback.format_exc()
if "no host given" in tbMsg: if "no host given" in tbMsg:
@ -534,10 +509,13 @@ class Connect:
responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, status) responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, status)
if responseHeaders: if responseHeaders:
logHeaders = "\n".join("%s: %s" % (key.capitalize() if isinstance(key, basestring) else key, getUnicode(value)) for (key, value) in responseHeaders.items()) logHeaders = "\n".join(
"%s: %s" % (key.capitalize() if isinstance(key, basestring) else key, getUnicode(value)) for (
key, value) in responseHeaders.items())
if not skipLogTraffic: if not skipLogTraffic:
logHTTPTraffic(requestMsg, "%s%s\n\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE])) logHTTPTraffic(requestMsg,
"%s%s\n\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]))
if conf.verbose <= 5: if conf.verbose <= 5:
responseMsg += getUnicode(logHeaders) responseMsg += getUnicode(logHeaders)
@ -549,7 +527,9 @@ class Connect:
return page, responseHeaders, code return page, responseHeaders, code
@staticmethod @staticmethod
def queryPage(value=None, place=None, content=False, getRatioValue=False, silent=False, method=None, timeBasedCompare=False, noteResponseTime=True, auxHeaders=None, response=False, raise404=None, removeReflection=True): def queryPage(value=None, place=None, content=False, getRatioValue=False, silent=False, method=None,
timeBasedCompare=False, noteResponseTime=True, auxHeaders=None, response=False, raise404=None,
removeReflection=True):
""" """
This method calls a function to get the target url page content This method calls a function to get the target url page content
and returns its page MD5 hash or a boolean value in case of and returns its page MD5 hash or a boolean value in case of
@ -614,7 +594,8 @@ class Connect:
else: else:
if place != PLACE.URI or (value and payload and '?' in value and value.find('?') < value.find(payload)): if place != PLACE.URI or (value and payload and '?' in value and value.find('?') < value.find(payload)):
# GET, URI and Cookie need to be throughly URL encoded (POST is encoded down below) # GET, URI and Cookie need to be throughly URL encoded (POST is encoded down below)
payload = urlencode(payload, '%', False, True) if place in (PLACE.GET, PLACE.COOKIE, PLACE.URI) and not skipUrlEncode else payload payload = urlencode(payload, '%', False, True) if place in (
PLACE.GET, PLACE.COOKIE, PLACE.URI) and not skipUrlEncode else payload
value = agent.replacePayload(value, payload) value = agent.replacePayload(value, payload)
if place: if place:
@ -630,7 +611,8 @@ class Connect:
post = conf.parameters[PLACE.POST] if place != PLACE.POST or not value else value post = conf.parameters[PLACE.POST] if place != PLACE.POST or not value else value
if PLACE.CUSTOM_POST in conf.parameters: if PLACE.CUSTOM_POST in conf.parameters:
post = conf.parameters[PLACE.CUSTOM_POST].replace(CUSTOM_INJECTION_MARK_CHAR, "") if place != PLACE.CUSTOM_POST or not value else value post = conf.parameters[PLACE.CUSTOM_POST].replace(CUSTOM_INJECTION_MARK_CHAR,
"") if place != PLACE.CUSTOM_POST or not value else value
if PLACE.COOKIE in conf.parameters: if PLACE.COOKIE in conf.parameters:
cookie = conf.parameters[PLACE.COOKIE] if place != PLACE.COOKIE or not value else value cookie = conf.parameters[PLACE.COOKIE] if place != PLACE.COOKIE or not value else value
@ -655,7 +637,8 @@ class Connect:
match = re.search("%s=(?P<value>[^&;]+)" % randomParameter, paramString) match = re.search("%s=(?P<value>[^&;]+)" % randomParameter, paramString)
if match: if match:
origValue = match.group("value") origValue = match.group("value")
retVal = re.sub("%s=[^&;]+" % randomParameter, "%s=%s" % (randomParameter, randomizeParameterValue(origValue)), paramString) retVal = re.sub("%s=[^&;]+" % randomParameter,
"%s=%s" % (randomParameter, randomizeParameterValue(origValue)), paramString)
return retVal return retVal
for randomParameter in conf.rParam: for randomParameter in conf.rParam:
@ -737,7 +720,8 @@ class Connect:
if conf.safUrl and conf.saFreq > 0: if conf.safUrl and conf.saFreq > 0:
kb.queryCounter += 1 kb.queryCounter += 1
if kb.queryCounter % conf.saFreq == 0: if kb.queryCounter % conf.saFreq == 0:
Connect.getPage(url=conf.safUrl, cookie=cookie, direct=True, silent=True, ua=ua, referer=referer, host=host) Connect.getPage(url=conf.safUrl, cookie=cookie, direct=True, silent=True, ua=ua, referer=referer,
host=host)
start = time.time() start = time.time()
@ -752,19 +736,25 @@ class Connect:
auxHeaders[HTTPHEADER.RANGE] = "bytes=-1" auxHeaders[HTTPHEADER.RANGE] = "bytes=-1"
_, headers, code = Connect.getPage(url=uri, get=get, post=post, cookie=cookie, ua=ua, referer=referer, host=host, silent=silent, method=method, auxHeaders=auxHeaders, raise404=raise404) _, headers, code = Connect.getPage(url=uri, get=get, post=post, cookie=cookie, ua=ua, referer=referer,
host=host, silent=silent, method=method, auxHeaders=auxHeaders, raise404=raise404)
if headers: if headers:
if kb.nullConnection == NULLCONNECTION.HEAD and HTTPHEADER.CONTENT_LENGTH in headers: if kb.nullConnection == NULLCONNECTION.HEAD and HTTPHEADER.CONTENT_LENGTH in headers:
pageLength = int(headers[HTTPHEADER.CONTENT_LENGTH]) pageLength = int(headers[HTTPHEADER.CONTENT_LENGTH])
elif kb.nullConnection == NULLCONNECTION.RANGE and HTTPHEADER.CONTENT_RANGE in headers: elif kb.nullConnection == NULLCONNECTION.RANGE and HTTPHEADER.CONTENT_RANGE in headers:
pageLength = int(headers[HTTPHEADER.CONTENT_RANGE][headers[HTTPHEADER.CONTENT_RANGE].find('/') + 1:]) pageLength = int(
headers[HTTPHEADER.CONTENT_RANGE][headers[HTTPHEADER.CONTENT_RANGE].find('/') + 1:])
if not pageLength: if not pageLength:
page, headers, code = Connect.getPage(url=uri, get=get, post=post, cookie=cookie, ua=ua, referer=referer, host=host, silent=silent, method=method, auxHeaders=auxHeaders, response=response, raise404=raise404, ignoreTimeout=timeBasedCompare) page, headers, code = Connect.getPage(url=uri, get=get, post=post, cookie=cookie, ua=ua, referer=referer,
host=host, silent=silent, method=method, auxHeaders=auxHeaders, response=response, raise404=raise404,
ignoreTimeout=timeBasedCompare)
if conf.secondOrder: if conf.secondOrder:
page, headers, code = Connect.getPage(url=conf.secondOrder, cookie=cookie, ua=ua, silent=silent, auxHeaders=auxHeaders, response=response, raise404=False, ignoreTimeout=timeBasedCompare, refreshing=True) page, headers, code = Connect.getPage(url=conf.secondOrder, cookie=cookie, ua=ua, silent=silent,
auxHeaders=auxHeaders, response=response, raise404=False, ignoreTimeout=timeBasedCompare,
refreshing=True)
threadData.lastQueryDuration = calculateDeltaSeconds(start) threadData.lastQueryDuration = calculateDeltaSeconds(start)
@ -788,7 +778,8 @@ class Connect:
return page, headers return page, headers
if getRatioValue: if getRatioValue:
return comparison(page, headers, code, getRatioValue=False, pageLength=pageLength), comparison(page, headers, code, getRatioValue=True, pageLength=pageLength) return comparison(page, headers, code, getRatioValue=False, pageLength=pageLength), comparison(page,
headers, code, getRatioValue=True, pageLength=pageLength)
elif pageLength or page: elif pageLength or page:
return comparison(page, headers, code, getRatioValue, pageLength) return comparison(page, headers, code, getRatioValue, pageLength)
else: else:

View File

@ -9,20 +9,11 @@ import time
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend, calculateDeltaSeconds, extractExpectedValue, getCurrentThreadData, \
from lib.core.common import calculateDeltaSeconds getUnicode, hashDBRetrieve, hashDBWrite, isListLike
from lib.core.common import extractExpectedValue from lib.core.data import conf, kb, logger
from lib.core.common import getCurrentThreadData
from lib.core.common import getUnicode
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import isListLike
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.dicts import SQL_STATEMENTS from lib.core.dicts import SQL_STATEMENTS
from lib.core.enums import DBMS from lib.core.enums import DBMS, EXPECTED
from lib.core.enums import EXPECTED
from lib.core.settings import UNICODE_ENCODING from lib.core.settings import UNICODE_ENCODING
from lib.utils.timeout import timeout from lib.utils.timeout import timeout

View File

@ -4,9 +4,7 @@
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
import os import os
import random
import re import re
import socket import socket
import threading import threading

View File

@ -10,41 +10,16 @@ import time
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.bigarray import BigArray from lib.core.bigarray import BigArray
from lib.core.common import Backend from lib.core.common import Backend, calculateDeltaSeconds, cleanQuery, expandAsteriskForColumns, \
from lib.core.common import calculateDeltaSeconds extractExpectedValue, getPublicTypeMembers, hashDBRetrieve, hashDBWrite, initTechnique, \
from lib.core.common import cleanQuery isNoneValue, isNumPosStrValue, isTechniqueAvailable, parseUnionPage, popValue, pushValue, readInput,\
from lib.core.common import expandAsteriskForColumns singleTimeWarnMessage
from lib.core.common import extractExpectedValue from lib.core.data import conf, kb, logger, queries
from lib.core.common import getPublicTypeMembers
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import initTechnique
from lib.core.common import isNoneValue
from lib.core.common import isNumPosStrValue
from lib.core.common import isTechniqueAvailable
from lib.core.common import parseUnionPage
from lib.core.common import popValue
from lib.core.common import pushValue
from lib.core.common import randomInt
from lib.core.common import readInput
from lib.core.common import safeStringFormat
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.data import queries
from lib.core.dicts import FROM_DUMMY_TABLE from lib.core.dicts import FROM_DUMMY_TABLE
from lib.core.enums import CHARSET_TYPE from lib.core.enums import CHARSET_TYPE, DBMS, EXPECTED, PAYLOAD
from lib.core.enums import DBMS from lib.core.exception import sqlmapNotVulnerableException, sqlmapUserQuitException
from lib.core.enums import EXPECTED from lib.core.settings import MAX_TECHNIQUES_PER_VALUE, SQL_SCALAR_REGEX
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapNotVulnerableException
from lib.core.exception import sqlmapUserQuitException
from lib.core.settings import MIN_TIME_RESPONSES
from lib.core.settings import MAX_TECHNIQUES_PER_VALUE
from lib.core.settings import SQL_SCALAR_REGEX
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
from lib.core.unescaper import unescaper
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request
from lib.request.direct import direct from lib.request.direct import direct
from lib.techniques.blind.inference import bisection from lib.techniques.blind.inference import bisection

View File

@ -18,7 +18,7 @@ class HTTPRangeHandler(urllib2.BaseHandler):
This was extremely simple. The Range header is a HTTP feature to This was extremely simple. The Range header is a HTTP feature to
begin with so all this class does is tell urllib2 that the begin with so all this class does is tell urllib2 that the
"206 Partial Content" reponse from the HTTP server is what we "206 Partial Content" response from the HTTP server is what we
expected. expected.
Example: Example:

View File

@ -8,18 +8,11 @@ See the file 'doc/COPYING' for copying permission
import urllib2 import urllib2
import urlparse import urlparse
from lib.core.data import conf from lib.core.data import kb, logger
from lib.core.data import kb from lib.core.common import getHostHeader, getUnicode, logHTTPTraffic, readInput
from lib.core.data import logger from lib.core.enums import HTTPHEADER, REDIRECTION
from lib.core.common import getHostHeader
from lib.core.common import getUnicode
from lib.core.common import logHTTPTraffic
from lib.core.common import readInput
from lib.core.enums import HTTPHEADER
from lib.core.enums import REDIRECTION
from lib.core.exception import sqlmapConnectionException from lib.core.exception import sqlmapConnectionException
from lib.core.settings import MAX_SINGLE_URL_REDIRECTIONS from lib.core.settings import MAX_SINGLE_URL_REDIRECTIONS, MAX_TOTAL_REDIRECTIONS
from lib.core.settings import MAX_TOTAL_REDIRECTIONS
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
from lib.request.basic import decodePage from lib.request.basic import decodePage

View File

@ -6,15 +6,9 @@ See the file 'doc/COPYING' for copying permission
""" """
from extra.safe2bin.safe2bin import safechardecode from extra.safe2bin.safe2bin import safechardecode
from lib.core.common import dataToStdout from lib.core.common import dataToStdout, Backend, getSQLSnippet, isTechniqueAvailable, readInput
from lib.core.common import Backend from lib.core.data import conf, logger
from lib.core.common import getSQLSnippet from lib.core.enums import DBMS, PAYLOAD
from lib.core.common import isTechniqueAvailable
from lib.core.common import readInput
from lib.core.data import conf
from lib.core.data import logger
from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapUnsupportedFeatureException from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.core.shell import autoCompletion from lib.core.shell import autoCompletion
from lib.request import inject from lib.request import inject
@ -25,7 +19,7 @@ from lib.takeover.xp_cmdshell import xp_cmdshell
class Abstraction(Web, UDF, xp_cmdshell): class Abstraction(Web, UDF, xp_cmdshell):
""" """
This class defines an abstraction layer for OS takeover functionalities This class defines an abstraction layer for OS takeover functionality
to UDF / xp_cmdshell objects to UDF / xp_cmdshell objects
""" """
@ -166,10 +160,10 @@ class Abstraction(Web, UDF, xp_cmdshell):
expression = getSQLSnippet(DBMS.MSSQL, "configure_openrowset", ENABLE="1") expression = getSQLSnippet(DBMS.MSSQL, "configure_openrowset", ENABLE="1")
inject.goStacked(expression) inject.goStacked(expression)
# TODO: add support for PostgreSQL # TODO: add support for PostgreSQL
#elif Backend.isDbms(DBMS.PGSQL): #elif Backend.isDbms(DBMS.PGSQL):
# expression = getSQLSnippet(DBMS.PGSQL, "configure_dblink", ENABLE="1") # expression = getSQLSnippet(DBMS.PGSQL, "configure_dblink", ENABLE="1")
# inject.goStacked(expression) # inject.goStacked(expression)
def initEnv(self, mandatory=True, detailed=False, web=False): def initEnv(self, mandatory=True, detailed=False, web=False):
self.__initRunAs() self.__initRunAs()

View File

@ -9,18 +9,11 @@ import os
import time import time
from extra.icmpsh.icmpsh_m import main as icmpshmaster from extra.icmpsh.icmpsh_m import main as icmpshmaster
from lib.core.common import getLocalIP from lib.core.common import getLocalIP, getRemoteIP, normalizePath, ntToPosixSlashes, randomStr, readInput
from lib.core.common import getRemoteIP from lib.core.data import conf, logger, paths
from lib.core.common import normalizePath
from lib.core.common import ntToPosixSlashes
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
class ICMPsh: class ICMPsh(object):
""" """
This class defines methods to call icmpsh for plugins. This class defines methods to call icmpsh for plugins.
""" """

View File

@ -12,35 +12,18 @@ import sys
import time import time
from select import select from select import select
from subprocess import PIPE from subprocess import PIPE, Popen as execute
from subprocess import Popen as execute
from lib.core.common import dataToStdout from lib.core.common import dataToStdout, Backend, getLocalIP, getRemoteIP, getUnicode, normalizePath,\
from lib.core.common import Backend ntToPosixSlashes, randomRange, randomStr, readInput
from lib.core.common import getLocalIP from lib.core.data import conf, logger, paths
from lib.core.common import getRemoteIP from lib.core.enums import DBMS, OS
from lib.core.common import getUnicode from lib.core.exception import sqlmapDataException, sqlmapFilePathException
from lib.core.common import normalizePath from lib.core.settings import IS_WIN, UNICODE_ENCODING
from lib.core.common import ntToPosixSlashes from lib.core.subprocessng import blockingReadFromFD, blockingWriteToFD, pollProcess, setNonBlocking
from lib.core.common import randomRange
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.enums import DBMS
from lib.core.enums import OS
from lib.core.exception import sqlmapDataException
from lib.core.exception import sqlmapFilePathException
from lib.core.settings import IS_WIN
from lib.core.settings import UNICODE_ENCODING
from lib.core.subprocessng import blockingReadFromFD
from lib.core.subprocessng import blockingWriteToFD
from lib.core.subprocessng import pollProcess
from lib.core.subprocessng import setNonBlocking
class Metasploit: class Metasploit(object):
""" """
This class defines methods to call Metasploit for plugins. This class defines methods to call Metasploit for plugins.
""" """
@ -66,60 +49,64 @@ class Metasploit:
self.__msfPayload = "%s & ruby %s" % (_, self.__msfPayload) self.__msfPayload = "%s & ruby %s" % (_, self.__msfPayload)
self.__msfPayloadsList = { self.__msfPayloadsList = {
"windows": { "windows": {
1: ( "Meterpreter (default)", "windows/meterpreter" ), 1: ( "Meterpreter (default)", "windows/meterpreter" ),
2: ( "Shell", "windows/shell" ), 2: ( "Shell", "windows/shell" ),
3: ( "VNC", "windows/vncinject" ), 3: ( "VNC", "windows/vncinject" ),
}, },
"linux": { "linux": {
1: ( "Shell (default)", "linux/x86/shell" ), 1: ( "Shell (default)", "linux/x86/shell" ),
2: ( "Meterpreter (beta)", "linux/x86/meterpreter" ), 2: ( "Meterpreter (beta)", "linux/x86/meterpreter" ),
} }
} }
self.__msfConnectionsList = { self.__msfConnectionsList = {
"windows": { "windows": {
1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ), 1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ),
2: ( "Reverse TCP: Try to connect back from the database host to this machine, on all ports between the specified and 65535", "reverse_tcp_allports" ), 2: (
3: ( "Reverse HTTP: Connect back from the database host to this machine tunnelling traffic over HTTP", "reverse_http" ), "Reverse TCP: Try to connect back from the database host to this machine, on all ports between the specified and 65535",
4: ( "Reverse HTTPS: Connect back from the database host to this machine tunnelling traffic over HTTPS", "reverse_https" ), "reverse_tcp_allports" ),
5: ( "Bind TCP: Listen on the database host for a connection", "bind_tcp" ) 3: ("Reverse HTTP: Connect back from the database host to this machine tunnelling traffic over HTTP",
}, "reverse_http" ),
"linux": { 4: ("Reverse HTTPS: Connect back from the database host to this machine tunnelling traffic over HTTPS",
1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ), "reverse_https" ),
2: ( "Bind TCP: Listen on the database host for a connection", "bind_tcp" ), 5: ( "Bind TCP: Listen on the database host for a connection", "bind_tcp" )
} },
} "linux": {
1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ),
2: ( "Bind TCP: Listen on the database host for a connection", "bind_tcp" ),
}
}
self.__msfEncodersList = { self.__msfEncodersList = {
"windows": { "windows": {
1: ( "No Encoder", "generic/none" ), 1: ( "No Encoder", "generic/none" ),
2: ( "Alpha2 Alphanumeric Mixedcase Encoder", "x86/alpha_mixed" ), 2: ( "Alpha2 Alphanumeric Mixedcase Encoder", "x86/alpha_mixed" ),
3: ( "Alpha2 Alphanumeric Uppercase Encoder", "x86/alpha_upper" ), 3: ( "Alpha2 Alphanumeric Uppercase Encoder", "x86/alpha_upper" ),
4: ( "Avoid UTF8/tolower", "x86/avoid_utf8_tolower" ), 4: ( "Avoid UTF8/tolower", "x86/avoid_utf8_tolower" ),
5: ( "Call+4 Dword XOR Encoder", "x86/call4_dword_xor" ), 5: ( "Call+4 Dword XOR Encoder", "x86/call4_dword_xor" ),
6: ( "Single-byte XOR Countdown Encoder", "x86/countdown" ), 6: ( "Single-byte XOR Countdown Encoder", "x86/countdown" ),
7: ( "Variable-length Fnstenv/mov Dword XOR Encoder", "x86/fnstenv_mov" ), 7: ( "Variable-length Fnstenv/mov Dword XOR Encoder", "x86/fnstenv_mov" ),
8: ( "Polymorphic Jump/Call XOR Additive Feedback Encoder", "x86/jmp_call_additive" ), 8: ( "Polymorphic Jump/Call XOR Additive Feedback Encoder", "x86/jmp_call_additive" ),
9: ( "Non-Alpha Encoder", "x86/nonalpha" ), 9: ( "Non-Alpha Encoder", "x86/nonalpha" ),
10: ( "Non-Upper Encoder", "x86/nonupper" ), 10: ( "Non-Upper Encoder", "x86/nonupper" ),
11: ( "Polymorphic XOR Additive Feedback Encoder (default)", "x86/shikata_ga_nai" ), 11: ( "Polymorphic XOR Additive Feedback Encoder (default)", "x86/shikata_ga_nai" ),
12: ( "Alpha2 Alphanumeric Unicode Mixedcase Encoder", "x86/unicode_mixed" ), 12: ( "Alpha2 Alphanumeric Unicode Mixedcase Encoder", "x86/unicode_mixed" ),
13: ( "Alpha2 Alphanumeric Unicode Uppercase Encoder", "x86/unicode_upper" ), 13: ( "Alpha2 Alphanumeric Unicode Uppercase Encoder", "x86/unicode_upper" ),
} }
} }
self.__msfSMBPortsList = { self.__msfSMBPortsList = {
"windows": { "windows": {
1: ( "139/TCP", "139" ), 1: ( "139/TCP", "139" ),
2: ( "445/TCP (default)", "445" ), 2: ( "445/TCP (default)", "445" ),
} }
} }
self.__portData = { self.__portData = {
"bind": "remote port number", "bind": "remote port number",
"reverse": "local port number", "reverse": "local port number",
} }
def __skeletonSelection(self, msg, lst=None, maxValue=1, default=1): def __skeletonSelection(self, msg, lst=None, maxValue=1, default=1):
if Backend.isOs(OS.WINDOWS): if Backend.isOs(OS.WINDOWS):
@ -360,7 +347,8 @@ class Metasploit:
self.__payloadCmd += " PrependChrootBreak=true PrependSetuid=true" self.__payloadCmd += " PrependChrootBreak=true PrependSetuid=true"
if extra == "BufferRegister=EAX": if extra == "BufferRegister=EAX":
self.__payloadCmd += " R | %s -a x86 -e %s -o \"%s\" -t %s" % (self.__msfEncode, self.encoderStr, outFile, format) self.__payloadCmd += " R | %s -a x86 -e %s -o \"%s\" -t %s" % (
self.__msfEncode, self.encoderStr, outFile, format)
if extra is not None: if extra is not None:
self.__payloadCmd += " %s" % extra self.__payloadCmd += " %s" % extra

View File

@ -32,19 +32,19 @@ class Registry:
readParse = "REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regValue + "\"" readParse = "REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regValue + "\""
self.__batRead = ( self.__batRead = (
"@ECHO OFF\r\n", "@ECHO OFF\r\n",
readParse readParse
) )
self.__batAdd = ( self.__batAdd = (
"@ECHO OFF\r\n", "@ECHO OFF\r\n",
"REG ADD \"%s\" /v \"%s\" /t %s /d %s /f" % (self.__regKey, self.__regValue, self.__regType, self.__regData) "REG ADD \"%s\" /v \"%s\" /t %s /d %s /f" % (self.__regKey, self.__regValue, self.__regType, self.__regData)
) )
self.__batDel = ( self.__batDel = (
"@ECHO OFF\r\n", "@ECHO OFF\r\n",
"REG DELETE \"%s\" /v \"%s\" /f" % (self.__regKey, self.__regValue) "REG DELETE \"%s\" /v \"%s\" /f" % (self.__regKey, self.__regValue)
) )
def __createLocalBatchFile(self): def __createLocalBatchFile(self):
self.__batPathFp = open(self.__batPathLocal, "w") self.__batPathFp = open(self.__batPathLocal, "w")

View File

@ -8,28 +8,16 @@ See the file 'doc/COPYING' for copying permission
import os import os
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import dataToStdout from lib.core.common import dataToStdout, Backend, isTechniqueAvailable, readInput
from lib.core.common import Backend from lib.core.data import conf, logger, queries
from lib.core.common import isTechniqueAvailable from lib.core.enums import DBMS, CHARSET_TYPE, EXPECTED, OS, PAYLOAD
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.data import queries
from lib.core.enums import DBMS
from lib.core.enums import CHARSET_TYPE
from lib.core.enums import EXPECTED
from lib.core.enums import OS
from lib.core.enums import PAYLOAD
from lib.core.common import unArrayizeValue from lib.core.common import unArrayizeValue
from lib.core.exception import sqlmapFilePathException from lib.core.exception import sqlmapFilePathException, sqlmapMissingMandatoryOptionException, \
from lib.core.exception import sqlmapMissingMandatoryOptionException sqlmapUnsupportedFeatureException, sqlmapUserQuitException
from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.core.exception import sqlmapUserQuitException
from lib.core.unescaper import unescaper from lib.core.unescaper import unescaper
from lib.request import inject from lib.request import inject
class UDF: class UDF(object):
""" """
This class defines methods to deal with User-Defined Functions for This class defines methods to deal with User-Defined Functions for
plugins. plugins.

View File

@ -14,42 +14,19 @@ from tempfile import mkstemp
from extra.cloak.cloak import decloak from extra.cloak.cloak import decloak
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import arrayizeValue from lib.core.common import arrayizeValue, Backend, decloakToNamedStream, extractRegexResult, getDirs, getDocRoot, \
from lib.core.common import Backend getPublicTypeMembers, getSQLSnippet, getUnicode, ntToPosixSlashes, isTechniqueAvailable, isWindowsDriveLetterPath,\
from lib.core.common import decloakToNamedStream normalizePath, posixToNtSlashes, randomInt, randomStr, readInput, singleTimeWarnMessage
from lib.core.common import extractRegexResult from lib.core.convert import hexencode, utf8encode
from lib.core.common import getDirs from lib.core.data import conf, kb, logger, paths
from lib.core.common import getDocRoot from lib.core.enums import DBMS, OS, PAYLOAD, WEB_API
from lib.core.common import getPublicTypeMembers from lib.core.settings import EVENTVALIDATION_REGEX, VIEWSTATE_REGEX
from lib.core.common import getSQLSnippet
from lib.core.common import getUnicode
from lib.core.common import ntToPosixSlashes
from lib.core.common import isTechniqueAvailable
from lib.core.common import isWindowsDriveLetterPath
from lib.core.common import normalizePath
from lib.core.common import posixToNtSlashes
from lib.core.common import randomInt
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.common import singleTimeWarnMessage
from lib.core.convert import hexencode
from lib.core.convert import utf8encode
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.enums import DBMS
from lib.core.enums import OS
from lib.core.enums import PAYLOAD
from lib.core.enums import WEB_API
from lib.core.settings import EVENTVALIDATION_REGEX
from lib.core.settings import VIEWSTATE_REGEX
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request
class Web: class Web(object):
""" """
This class defines web-oriented OS takeover functionalities for This class defines web-oriented OS takeover functionality for
plugins. plugins.
""" """

View File

@ -6,34 +6,16 @@ See the file 'doc/COPYING' for copying permission
""" """
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend, getLimitRange, getSQLSnippet, hashDBWrite, isListLike, isNoneValue, \
from lib.core.common import getLimitRange isNumPosStrValue, isTechniqueAvailable, pushValue, popValue, randomStr, readInput, wasLastRequestDelayed
from lib.core.common import getSQLSnippet
from lib.core.common import hashDBWrite
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 pushValue
from lib.core.common import popValue
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.common import wasLastRequestDelayed
from lib.core.convert import hexencode from lib.core.convert import hexencode
from lib.core.data import conf from lib.core.data import conf, kb, logger
from lib.core.data import kb from lib.core.enums import CHARSET_TYPE, DBMS, EXPECTED, HASHDB_KEYS, PAYLOAD
from lib.core.data import logger
from lib.core.enums import CHARSET_TYPE
from lib.core.enums import DBMS
from lib.core.enums import EXPECTED
from lib.core.enums import HASHDB_KEYS
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapUnsupportedFeatureException from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData
from lib.core.unescaper import unescaper
from lib.request import inject from lib.request import inject
class xp_cmdshell: class xp_cmdshell(object):
""" """
This class defines methods to deal with Microsoft SQL Server This class defines methods to deal with Microsoft SQL Server
xp_cmdshell extended procedure for plugins. xp_cmdshell extended procedure for plugins.

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -5,49 +5,22 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
import re
import threading import threading
import time import time
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend, calculateDeltaSeconds, dataToStdout, decodeHexValue, decodeIntToUnicode,\
from lib.core.common import calculateDeltaSeconds filterControlChars, getCharset, getCounter, goGoodSamaritan, getPartRun, hashDBRetrieve, hashDBWrite,\
from lib.core.common import dataToStdout incrementCounter, safeStringFormat, singleTimeWarnMessage
from lib.core.common import decodeHexValue from lib.core.data import conf, kb, logger, queries
from lib.core.common import decodeIntToUnicode from lib.core.enums import ADJUST_TIME_DELAY, CHARSET_TYPE, DBMS, PAYLOAD
from lib.core.common import filterControlChars
from lib.core.common import getCharset
from lib.core.common import getCounter
from lib.core.common import goGoodSamaritan
from lib.core.common import getPartRun
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import incrementCounter
from lib.core.common import randomStr
from lib.core.common import safeStringFormat
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.data import queries
from lib.core.enums import ADJUST_TIME_DELAY
from lib.core.enums import CHARSET_TYPE
from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapThreadException from lib.core.exception import sqlmapThreadException
from lib.core.progress import ProgressBar from lib.core.progress import ProgressBar
from lib.core.settings import CHAR_INFERENCE_MARK from lib.core.settings import CHAR_INFERENCE_MARK, INFERENCE_BLANK_BREAK, INFERENCE_UNKNOWN_CHAR,\
from lib.core.settings import INFERENCE_BLANK_BREAK INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR, INFERENCE_NOT_EQUALS_CHAR, MAX_TIME_REVALIDATION_STEPS,\
from lib.core.settings import INFERENCE_UNKNOWN_CHAR PARTIAL_VALUE_MARKER, VALID_TIME_CHARS_RUN_THRESHOLD
from lib.core.settings import INFERENCE_GREATER_CHAR from lib.core.threads import getCurrentThreadData, runThreads
from lib.core.settings import INFERENCE_EQUALS_CHAR
from lib.core.settings import INFERENCE_NOT_EQUALS_CHAR
from lib.core.settings import MAX_TIME_REVALIDATION_STEPS
from lib.core.settings import PARTIAL_VALUE_MARKER
from lib.core.settings import VALID_TIME_CHARS_RUN_THRESHOLD
from lib.core.threads import getCurrentThreadData
from lib.core.threads import runThreads
from lib.core.unescaper import unescaper from lib.core.unescaper import unescaper
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -7,37 +7,19 @@ See the file 'doc/COPYING' for copying permission
import time import time
from lib.core.common import clearConsoleLine from lib.core.common import clearConsoleLine, dataToStdout, filterListValue, getFileItems, Backend, \
from lib.core.common import dataToStdout getPageWordSet, hashDBWrite, randomInt, randomStr, safeStringFormat, safeSQLIdentificatorNaming
from lib.core.common import filterListValue from lib.core.data import conf, kb, logger
from lib.core.common import getFileItems from lib.core.enums import DBMS, HASHDB_KEYS
from lib.core.common import Backend from lib.core.exception import sqlmapDataException, sqlmapMissingMandatoryOptionException
from lib.core.common import getPageWordSet from lib.core.settings import METADB_SUFFIX, BRUTE_COLUMN_EXISTS_TEMPLATE, BRUTE_TABLE_EXISTS_TEMPLATE
from lib.core.common import hashDBRetrieve from lib.core.threads import getCurrentThreadData, runThreads
from lib.core.common import hashDBWrite
from lib.core.common import randomInt
from lib.core.common import randomStr
from lib.core.common import safeStringFormat
from lib.core.common import safeSQLIdentificatorNaming
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 HASHDB_KEYS
from lib.core.exception import sqlmapDataException
from lib.core.exception import sqlmapMissingMandatoryOptionException
from lib.core.settings import METADB_SUFFIX
from lib.core.settings import BRUTE_COLUMN_EXISTS_TEMPLATE
from lib.core.settings import BRUTE_TABLE_EXISTS_TEMPLATE
from lib.core.threads import getCurrentThreadData
from lib.core.threads import runThreads
from lib.request import inject from lib.request import inject
def __addPageTextWords(): def __addPageTextWords():
wordsList = [] wordsList = []
infoMsg = "adding words used on web page to the check list" logger.info("adding words used on web page to the check list")
logger.info(infoMsg)
pageWords = getPageWordSet(kb.originalPage) pageWords = getPageWordSet(kb.originalPage)
for word in pageWords: for word in pageWords:
@ -58,8 +40,7 @@ def tableExists(tableFile, regex=None):
tables = getFileItems(tableFile, lowercase=Backend.getIdentifiedDbms() in (DBMS.ACCESS,), unique=True) tables = getFileItems(tableFile, lowercase=Backend.getIdentifiedDbms() in (DBMS.ACCESS,), unique=True)
infoMsg = "checking table existence using items from '%s'" % tableFile logger.info("checking table existence using items from '%s'" % tableFile)
logger.info(infoMsg)
tables.extend(__addPageTextWords()) tables.extend(__addPageTextWords())
tables = filterListValue(tables, regex) tables = filterListValue(tables, regex)

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -7,9 +7,7 @@ See the file 'doc/COPYING' for copying permission
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.common import randomInt from lib.core.common import randomInt
from lib.core.data import conf from lib.core.data import conf, kb, logger
from lib.core.data import kb
from lib.core.data import logger
from lib.core.dicts import FROM_DUMMY_TABLE from lib.core.dicts import FROM_DUMMY_TABLE
from lib.core.exception import sqlmapNotVulnerableException from lib.core.exception import sqlmapNotVulnerableException
from lib.techniques.dns.use import dnsUse from lib.techniques.dns.use import dnsUse
@ -19,7 +17,8 @@ def dnsTest(payload):
logger.info("testing for data retrieval through DNS channel") logger.info("testing for data retrieval through DNS channel")
randInt = randomInt() randInt = randomInt()
kb.dnsTest = dnsUse(payload, "SELECT %d%s" % (randInt, FROM_DUMMY_TABLE.get(Backend.getIdentifiedDbms(), ""))) == str(randInt) kb.dnsTest = dnsUse(payload,
"SELECT %d%s" % (randInt, FROM_DUMMY_TABLE.get(Backend.getIdentifiedDbms(), ""))) == str(randInt)
if not kb.dnsTest: if not kb.dnsTest:
errMsg = "data retrieval through DNS channel failed" errMsg = "data retrieval through DNS channel failed"

View File

@ -7,23 +7,11 @@ See the file 'doc/COPYING' for copying permission
import re import re
import time import time
import string
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend, calculateDeltaSeconds, dataToStdout, decodeHexValue, extractRegexResult,\
from lib.core.common import calculateDeltaSeconds getSQLSnippet, hashDBRetrieve, hashDBWrite, randomInt, randomStr, safeStringFormat, singleTimeWarnMessage
from lib.core.common import dataToStdout
from lib.core.common import decodeHexValue
from lib.core.common import extractRegexResult
from lib.core.common import getSQLSnippet
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import randomInt
from lib.core.common import randomStr
from lib.core.common import safecharencode
from lib.core.common import safeStringFormat
from lib.core.common import singleTimeWarnMessage
from lib.core.data import conf from lib.core.data import conf
from lib.core.data import kb from lib.core.data import kb
from lib.core.data import logger from lib.core.data import logger

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -11,38 +11,16 @@ import time
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.bigarray import BigArray from lib.core.bigarray import BigArray
from lib.core.common import Backend from lib.core.common import Backend, calculateDeltaSeconds, dataToStdout, decodeHexValue, extractRegexResult,\
from lib.core.common import calculateDeltaSeconds getUnicode, hashDBRetrieve, hashDBWrite, incrementCounter, initTechnique, isListLike, isNumPosStrValue,\
from lib.core.common import dataToStdout listToStrValue, readInput
from lib.core.common import decodeHexValue
from lib.core.common import extractRegexResult
from lib.core.common import getUnicode
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import incrementCounter
from lib.core.common import initTechnique
from lib.core.common import isListLike
from lib.core.common import isNumPosStrValue
from lib.core.common import listToStrValue
from lib.core.common import readInput
from lib.core.convert import htmlunescape from lib.core.convert import htmlunescape
from lib.core.data import conf from lib.core.data import conf, kb, logger, queries
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import queries
from lib.core.dicts import FROM_DUMMY_TABLE from lib.core.dicts import FROM_DUMMY_TABLE
from lib.core.enums import DBMS from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD, MYSQL_ERROR_CHUNK_LENGTH, MSSQL_ERROR_CHUNK_LENGTH, \
from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD NULL, PARTIAL_VALUE_MARKER, SLOW_ORDER_COUNT_THRESHOLD, SQL_SCALAR_REGEX, TURN_OFF_RESUME_INFO_LIMIT
from lib.core.settings import MYSQL_ERROR_CHUNK_LENGTH from lib.core.threads import getCurrentThreadData, runThreads
from lib.core.settings import MSSQL_ERROR_CHUNK_LENGTH
from lib.core.settings import NULL
from lib.core.settings import PARTIAL_VALUE_MARKER
from lib.core.settings import SLOW_ORDER_COUNT_THRESHOLD
from lib.core.settings import SQL_SCALAR_REGEX
from lib.core.settings import TURN_OFF_RESUME_INFO_LIMIT
from lib.core.threads import getCurrentThreadData
from lib.core.threads import runThreads
from lib.core.unescaper import unescaper from lib.core.unescaper import unescaper
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request

View File

@ -11,39 +11,17 @@ import time
from extra.safe2bin.safe2bin import safecharencode from extra.safe2bin.safe2bin import safecharencode
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.bigarray import BigArray from lib.core.bigarray import BigArray
from lib.core.common import arrayizeValue from lib.core.common import arrayizeValue, Backend, calculateDeltaSeconds, clearConsoleLine, dataToStdout, \
from lib.core.common import Backend extractRegexResult, flattenValue, getConsoleWidth, getUnicode, hashDBRetrieve, hashDBWrite, incrementCounter, \
from lib.core.common import calculateDeltaSeconds initTechnique, isNoneValue, isNumPosStrValue, listToStrValue, parseUnionPage, removeReflectiveValues,\
from lib.core.common import clearConsoleLine singleTimeWarnMessage, wasLastRequestDBMSError
from lib.core.common import dataToStdout
from lib.core.common import extractRegexResult
from lib.core.common import flattenValue
from lib.core.common import getConsoleWidth
from lib.core.common import getUnicode
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import incrementCounter
from lib.core.common import initTechnique
from lib.core.common import isNoneValue
from lib.core.common import isNumPosStrValue
from lib.core.common import listToStrValue
from lib.core.common import parseUnionPage
from lib.core.common import removeReflectiveValues
from lib.core.common import singleTimeWarnMessage
from lib.core.common import wasLastRequestDBMSError
from lib.core.convert import htmlunescape from lib.core.convert import htmlunescape
from lib.core.data import conf from lib.core.data import conf,kb, logger, queries
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import queries
from lib.core.dicts import FROM_DUMMY_TABLE from lib.core.dicts import FROM_DUMMY_TABLE
from lib.core.enums import DBMS from lib.core.enums import DBMS, PAYLOAD
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapSyntaxException from lib.core.exception import sqlmapSyntaxException
from lib.core.settings import SQL_SCALAR_REGEX from lib.core.settings import SQL_SCALAR_REGEX, TURN_OFF_RESUME_INFO_LIMIT
from lib.core.settings import TURN_OFF_RESUME_INFO_LIMIT from lib.core.threads import getCurrentThreadData, runThreads
from lib.core.threads import getCurrentThreadData
from lib.core.threads import runThreads
from lib.core.unescaper import unescaper from lib.core.unescaper import unescaper
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request

View File

@ -5,21 +5,19 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
import re from re import sub, search
from lib.core.common import readXmlFile from lib.core.common import readXmlFile, urldecode
from lib.core.common import urldecode from lib.core.data import paths, logger
from lib.core.data import paths
from lib.core.data import logger
rules = None rules = None
def __adjustGrammar(string): def __adjustGrammar(string):
string = re.sub('\ADetects', 'Detected', string) string = sub('\ADetects', 'Detected', string)
string = re.sub('\Afinds', 'Found', string) string = sub('\Afinds', 'Found', string)
string = re.sub('attempts\Z', 'attempt', string) string = sub('attempts\Z', 'attempt', string)
string = re.sub('injections\Z', 'injection', string) string = sub('injections\Z', 'injection', string)
string = re.sub('attacks\Z', 'attack', string) string = sub('attacks\Z', 'attack', string)
return string return string
@ -48,7 +46,7 @@ def checkPayload(payload):
if payload: if payload:
for rule, desc in rules: for rule, desc in rules:
if re.search(rule, payload): if search(rule, payload):
detected = True detected = True
logger.warn("highly probable IDS/IPS detection: '%s: %s'" % (desc, payload)) logger.warn("highly probable IDS/IPS detection: '%s: %s'" % (desc, payload))

View File

@ -10,17 +10,11 @@ import re
import urlparse import urlparse
import time import time
from lib.core.common import clearConsoleLine from lib.core.common import clearConsoleLine, dataToStdout, findPageForms, singleTimeWarnMessage
from lib.core.common import dataToStdout from lib.core.data import conf, kb, logger
from lib.core.common import findPageForms
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.exception import sqlmapConnectionException from lib.core.exception import sqlmapConnectionException
from lib.core.settings import CRAWL_EXCLUDE_EXTENSIONS from lib.core.settings import CRAWL_EXCLUDE_EXTENSIONS
from lib.core.threads import getCurrentThreadData from lib.core.threads import getCurrentThreadData, runThreads
from lib.core.threads import runThreads
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request
from thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup from thirdparty.beautifulsoup.beautifulsoup import BeautifulSoup
from thirdparty.oset.pyoset import oset from thirdparty.oset.pyoset import oset

View File

@ -12,21 +12,12 @@ import socket
import urllib import urllib
import urllib2 import urllib2
from lib.core.common import getUnicode from lib.core.common import getUnicode, urlencode
from lib.core.common import readInput from lib.core.data import conf, logger
from lib.core.common import urldecode from lib.core.exception import sqlmapConnectionException, sqlmapGenericException
from lib.core.common import urlencode from lib.core.settings import GOOGLE_REGEX, UNICODE_ENCODING, decodePage
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapGenericException
from lib.core.settings import GOOGLE_REGEX
from lib.core.settings import UNICODE_ENCODING
from lib.core.settings import URI_INJECTABLE_REGEX
from lib.request.basic import decodePage
class Google: class Google(object):
""" """
This class defines methods used to perform Google dorking (command This class defines methods used to perform Google dorking (command
line option '-g <google dork>' line option '-g <google dork>'

View File

@ -30,43 +30,16 @@ from hashlib import md5
from hashlib import sha1 from hashlib import sha1
from Queue import Queue from Queue import Queue
from lib.core.common import Backend from lib.core.common import Backend, checkFile, clearConsoleLine, dataToStdout, getFileItems, getPublicTypeMembers,\
from lib.core.common import checkFile hashDBRetrieve, hashDBWrite, normalizeUnicode, paths, readInput, singleTimeLogMessage, singleTimeWarnMessage
from lib.core.common import clearConsoleLine from lib.core.convert import hexdecode, hexencode, utf8encode
from lib.core.common import dataToStdout from lib.core.data import conf, kb, logger
from lib.core.common import getFileItems from lib.core.enums import DBMS, HASH
from lib.core.common import getPublicTypeMembers from lib.core.exception import sqlmapFilePathException, sqlmapUserQuitException
from lib.core.common import hashDBRetrieve from lib.core.settings import COMMON_PASSWORD_SUFFIXES, COMMON_USER_COLUMNS, DUMMY_USER_PREFIX, HASH_MOD_ITEM_DISPLAY,\
from lib.core.common import hashDBWrite HASH_RECOGNITION_QUIT_THRESHOLD, IS_WIN, ITOA64, ML, NULL, UNICODE_ENCODING, ROTATING_CHARS
from lib.core.common import normalizeUnicode
from lib.core.common import paths
from lib.core.common import readInput
from lib.core.common import singleTimeLogMessage
from lib.core.common import singleTimeWarnMessage
from lib.core.convert import hexdecode
from lib.core.convert import hexencode
from lib.core.convert import utf8encode
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 HASH
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapUserQuitException
from lib.core.settings import COMMON_PASSWORD_SUFFIXES
from lib.core.settings import COMMON_USER_COLUMNS
from lib.core.settings import DUMMY_USER_PREFIX
from lib.core.settings import HASH_MOD_ITEM_DISPLAY
from lib.core.settings import HASH_RECOGNITION_QUIT_THRESHOLD
from lib.core.settings import IS_WIN
from lib.core.settings import ITOA64
from lib.core.settings import ML
from lib.core.settings import NULL
from lib.core.settings import UNICODE_ENCODING
from lib.core.settings import ROTATING_CHARS
from lib.core.wordlist import Wordlist from lib.core.wordlist import Wordlist
from thirdparty.pydes.pyDes import des from thirdparty.pydes.pyDes import des, CBC
from thirdparty.pydes.pyDes import CBC
def mysql_passwd(password, uppercase=True): def mysql_passwd(password, uppercase=True):
""" """

View File

@ -11,16 +11,11 @@ import sqlite3
import threading import threading
import time import time
from lib.core.common import getUnicode from lib.core.common import getUnicode, serializeObject, unserializeObject
from lib.core.common import serializeObject
from lib.core.common import unserializeObject
from lib.core.data import logger from lib.core.data import logger
from lib.core.exception import sqlmapDataException from lib.core.exception import sqlmapDataException
from lib.core.settings import HASHDB_FLUSH_RETRIES from lib.core.settings import HASHDB_FLUSH_RETRIES, HASHDB_FLUSH_THRESHOLD, UNICODE_ENCODING
from lib.core.settings import HASHDB_FLUSH_THRESHOLD from lib.core.threads import getCurrentThreadData, getCurrentThreadName
from lib.core.settings import UNICODE_ENCODING
from lib.core.threads import getCurrentThreadData
from lib.core.threads import getCurrentThreadName
class HashDB(object): class HashDB(object):
def __init__(self, filepath): def __init__(self, filepath):

View File

@ -7,21 +7,11 @@ See the file 'doc/COPYING' for copying permission
from extra.safe2bin.safe2bin import safechardecode from extra.safe2bin.safe2bin import safechardecode
from lib.core.bigarray import BigArray from lib.core.bigarray import BigArray
from lib.core.common import Backend from lib.core.common import Backend, isNoneValue, isNumPosStrValue, singleTimeWarnMessage, unArrayizeValue, \
from lib.core.common import decodeIntToUnicode unsafeSQLIdentificatorNaming
from lib.core.common import isNoneValue from lib.core.data import conf, logger, queries
from lib.core.common import isNumPosStrValue from lib.core.enums import CHARSET_TYPE, EXPECTED
from lib.core.common import singleTimeWarnMessage from lib.core.exception import sqlmapConnectionException, sqlmapNoneDataException
from lib.core.common import unArrayizeValue
from lib.core.common import unsafeSQLIdentificatorNaming
from lib.core.data import conf
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.exception import sqlmapConnectionException
from lib.core.exception import sqlmapNoneDataException
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
from lib.core.settings import MAX_INT from lib.core.settings import MAX_INT
from lib.core.unescaper import unescaper from lib.core.unescaper import unescaper
from lib.request import inject from lib.request import inject

View File

@ -4,5 +4,3 @@
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -5,4 +5,3 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
pass

View File

@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
try: try:
import pyodbc import pyodbc
except ImportError, _: except ImportError:
pass pass
import logging import logging

View File

@ -7,15 +7,8 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.common import Backend from lib.core.common import Backend, Format, getCurrentThreadData, randomInt, randomStr, wasLastRequestDBMSError
from lib.core.common import Format from lib.core.data import conf, kb, logger
from lib.core.common import getCurrentThreadData
from lib.core.common import randomInt
from lib.core.common import randomStr
from lib.core.common import wasLastRequestDBMSError
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 DBMS
from lib.core.session import setDbms from lib.core.session import setDbms
from lib.core.settings import ACCESS_ALIASES from lib.core.settings import ACCESS_ALIASES
@ -49,11 +42,11 @@ class Fingerprint(GenericFingerprint):
# Microsoft Access table reference updated on 01/2010 # Microsoft Access table reference updated on 01/2010
sysTables = { sysTables = {
"97": ("MSysModules2", "MSysAccessObjects"), "97": ("MSysModules2", "MSysAccessObjects"),
"2000" : ("!MSysModules2", "MSysAccessObjects"), "2000": ("!MSysModules2", "MSysAccessObjects"),
"2002-2003" : ("MSysAccessStorage", "!MSysNavPaneObjectIDs"), "2002-2003": ("MSysAccessStorage", "!MSysNavPaneObjectIDs"),
"2007" : ("MSysAccessStorage", "MSysNavPaneObjectIDs") "2007": ("MSysAccessStorage", "MSysNavPaneObjectIDs")
} }
# MSysAccessXML is not a reliable system table because it doesn't always exist # 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") # ("Access through Access", p6, should be "normally doesn't exist" instead of "is normally empty")
@ -68,7 +61,8 @@ class Fingerprint(GenericFingerprint):
table = table[1:] table = table[1:]
randInt = randomInt() randInt = randomInt()
result = inject.checkBooleanExpression("EXISTS(SELECT * FROM %s WHERE %d=%d)" % (table, randInt, randInt)) result = inject.checkBooleanExpression(
"EXISTS(SELECT * FROM %s WHERE %d=%d)" % (table, randInt, randInt))
if result is None: if result is None:
result = False result = False
@ -93,7 +87,8 @@ class Fingerprint(GenericFingerprint):
randInt = randomInt() randInt = randomInt()
randStr = randomStr() randStr = randomStr()
_ = inject.checkBooleanExpression("EXISTS(SELECT * FROM %s.%s WHERE %d=%d)" % (randStr, randStr, randInt, randInt)) _ = inject.checkBooleanExpression(
"EXISTS(SELECT * FROM %s.%s WHERE %d=%d)" % (randStr, randStr, randInt, randInt))
if wasLastRequestDBMSError(): if wasLastRequestDBMSError():
threadData = getCurrentThreadData() threadData = getCurrentThreadData()

View File

@ -12,8 +12,7 @@ except ImportError, _:
import logging import logging
from lib.core.data import conf from lib.core.data import conf, logger
from lib.core.data import logger
from lib.core.exception import sqlmapConnectionException from lib.core.exception import sqlmapConnectionException
from plugins.generic.connector import Connector as GenericConnector from plugins.generic.connector import Connector as GenericConnector

View File

@ -1,20 +1,19 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
$Id$ $Id$
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.data import logger from lib.core.data import logger
from plugins.generic.enumeration import Enumeration as GenericEnumeration from plugins.generic.enumeration import Enumeration as GenericEnumeration
class Enumeration(GenericEnumeration): class Enumeration(GenericEnumeration):
def __init__(self): def __init__(self):
GenericEnumeration.__init__(self) GenericEnumeration.__init__(self)
def getPasswordHashes(self): def getPasswordHashes(self):
warnMsg = "on DB2 it is not possible to list password hashes" warnMsg = "on DB2 it is not possible to list password hashes"
logger.warn(warnMsg) logger.warn(warnMsg)

View File

@ -6,14 +6,9 @@ See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend, Format, randomInt
from lib.core.common import Format from lib.core.data import conf, kb, logger
from lib.core.common import randomInt from lib.core.enums import DBMS, OS
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.session import setDbms
from lib.core.settings import DB2_ALIASES from lib.core.settings import DB2_ALIASES
from lib.request import inject from lib.request import inject

View File

@ -7,19 +7,11 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.common import Backend from lib.core.common import Backend, Format, getUnicode, randomInt, randomRange
from lib.core.common import Format from lib.core.data import conf, kb, logger
from lib.core.common import getUnicode
from lib.core.common import randomInt
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.enums import DBMS
from lib.core.session import setDbms from lib.core.session import setDbms
from lib.core.settings import FIREBIRD_ALIASES from lib.core.settings import FIREBIRD_ALIASES, METADB_SUFFIX, UNKNOWN_DBMS_VERSION
from lib.core.settings import METADB_SUFFIX
from lib.core.settings import UNKNOWN_DBMS_VERSION
from lib.request import inject from lib.request import inject
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint from plugins.generic.fingerprint import Fingerprint as GenericFingerprint

View File

@ -8,9 +8,7 @@ See the file 'doc/COPYING' for copying permission
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.common import Format from lib.core.common import Format
from lib.core.data import conf from lib.core.data import conf, kb, logger
from lib.core.data import kb
from lib.core.data import logger
from lib.core.enums import DBMS from lib.core.enums import DBMS
from lib.core.session import setDbms from lib.core.session import setDbms
from lib.core.settings import MAXDB_ALIASES from lib.core.settings import MAXDB_ALIASES

View File

@ -6,22 +6,10 @@ See the file 'doc/COPYING' for copying permission
""" """
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import arrayizeValue from lib.core.common import arrayizeValue, Backend, getLimitRange, isInferenceAvailable, isNoneValue,\
from lib.core.common import Backend isNumPosStrValue, isTechniqueAvailable, safeSQLIdentificatorNaming, unsafeSQLIdentificatorNaming
from lib.core.common import getLimitRange from lib.core.data import conf, kb, logger, queries
from lib.core.common import isInferenceAvailable from lib.core.enums import CHARSET_TYPE, EXPECTED, PAYLOAD
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.exception import sqlmapNoneDataException
from lib.core.settings import CURRENT_DB from lib.core.settings import CURRENT_DB
from lib.request import inject from lib.request import inject

View File

@ -9,20 +9,12 @@ import codecs
import ntpath import ntpath
import os import os
from lib.core.common import getLimitRange from lib.core.common import getLimitRange, isNumPosStrValue, isTechniqueAvailable, posixToNtSlashes, \
from lib.core.common import isNumPosStrValue randomStr, readInput
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 hexencode from lib.core.convert import hexencode
from lib.core.data import conf from lib.core.data import conf, logger
from lib.core.data import logger from lib.core.enums import CHARSET_TYPE, EXPECTED, PAYLOAD
from lib.core.enums import CHARSET_TYPE from lib.core.exception import sqlmapNoneDataException, sqlmapUnsupportedFeatureException
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 lib.request import inject
from plugins.generic.filesystem import Filesystem as GenericFilesystem from plugins.generic.filesystem import Filesystem as GenericFilesystem

View File

@ -5,15 +5,9 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend, Format, getUnicode, randomInt
from lib.core.common import Format from lib.core.data import conf, kb, logger
from lib.core.common import getUnicode from lib.core.enums import DBMS, OS
from lib.core.common import randomInt
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.session import setDbms
from lib.core.settings import MSSQL_ALIASES from lib.core.settings import MSSQL_ALIASES
from lib.request import inject from lib.request import inject

View File

@ -23,11 +23,11 @@ class MySQLMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Take
def __init__(self): def __init__(self):
self.excludeDbsList = MYSQL_SYSTEM_DBS self.excludeDbsList = MYSQL_SYSTEM_DBS
self.sysUdfs = { self.sysUdfs = {
# UDF name: UDF return data-type # UDF name: UDF return data-type
"sys_exec": { "return": "int" }, "sys_exec": {"return": "int"},
"sys_eval": { "return": "string" }, "sys_eval": {"return": "string"},
"sys_bineval": { "return": "int" } "sys_bineval": {"return": "int"}
} }
Syntax.__init__(self) Syntax.__init__(self)
Fingerprint.__init__(self) Fingerprint.__init__(self)

View File

@ -7,13 +7,12 @@ See the file 'doc/COPYING' for copying permission
try: try:
import pymysql import pymysql
except ImportError, _: except ImportError:
pass pass
import logging import logging
from lib.core.data import conf from lib.core.data import conf, logger
from lib.core.data import logger
from lib.core.exception import sqlmapConnectionException from lib.core.exception import sqlmapConnectionException
from plugins.generic.connector import Connector as GenericConnector from plugins.generic.connector import Connector as GenericConnector

View File

@ -5,17 +5,9 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import isNumPosStrValue from lib.core.common import isNumPosStrValue, isTechniqueAvailable, randomStr, singleTimeWarnMessage
from lib.core.common import isTechniqueAvailable from lib.core.data import conf, kb, logger
from lib.core.common import randomStr from lib.core.enums import CHARSET_TYPE, EXPECTED, PAYLOAD, PLACE
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.core.exception import sqlmapNoneDataException
from lib.request import inject from lib.request import inject
from lib.techniques.union.use import unionUse from lib.techniques.union.use import unionUse

View File

@ -7,15 +7,9 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.common import Backend from lib.core.common import Backend, Format, getUnicode, randomInt
from lib.core.common import Format from lib.core.data import conf, kb, logger
from lib.core.common import getUnicode from lib.core.enums import DBMS, OS
from lib.core.common import randomInt
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.session import setDbms
from lib.core.settings import MYSQL_ALIASES from lib.core.settings import MYSQL_ALIASES
from lib.core.settings import UNKNOWN_DBMS_VERSION from lib.core.settings import UNKNOWN_DBMS_VERSION
@ -41,17 +35,17 @@ class Fingerprint(GenericFingerprint):
# MySQL valid versions updated on 04/2011 # MySQL valid versions updated on 04/2011
versions = ( versions = (
(32200, 32235), # MySQL 3.22 (32200, 32235), # MySQL 3.22
(32300, 32359), # MySQL 3.23 (32300, 32359), # MySQL 3.23
(40000, 40032), # MySQL 4.0 (40000, 40032), # MySQL 4.0
(40100, 40131), # MySQL 4.1 (40100, 40131), # MySQL 4.1
(50000, 50092), # MySQL 5.0 (50000, 50092), # MySQL 5.0
(50100, 50156), # MySQL 5.1 (50100, 50156), # MySQL 5.1
(50400, 50404), # MySQL 5.4 (50400, 50404), # MySQL 5.4
(50500, 50521), # MySQL 5.5 (50500, 50521), # MySQL 5.5
(50600, 50604), # MySQL 5.6 (50600, 50604), # MySQL 5.6
(60000, 60014), # MySQL 6.0 (60000, 60014), # MySQL 6.0
) )
index = -1 index = -1
for i in xrange(len(versions)): for i in xrange(len(versions)):

View File

@ -8,17 +8,9 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend, isTechniqueAvailable, normalizePath, ntToPosixSlashes, randomStr, unArrayizeValue
from lib.core.common import isTechniqueAvailable from lib.core.data import kb, logger, paths
from lib.core.common import normalizePath from lib.core.enums import OS, PAYLOAD
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.core.enums import PAYLOAD
from lib.request import inject from lib.request import inject
from lib.request.connect import Connect as Request from lib.request.connect import Connect as Request
from plugins.generic.takeover import Takeover as GenericTakeover from plugins.generic.takeover import Takeover as GenericTakeover
@ -93,7 +85,8 @@ class Takeover(GenericTakeover):
# Reference: http://dev.mysql.com/doc/refman/5.1/en/create-function-udf.html # Reference: http://dev.mysql.com/doc/refman/5.1/en/create-function-udf.html
inject.goStacked("DROP FUNCTION %s" % udf) inject.goStacked("DROP FUNCTION %s" % udf)
inject.goStacked("CREATE FUNCTION %s RETURNS %s SONAME '%s.%s'" % (udf, ret, self.udfSharedLibName, self.udfSharedLibExt)) inject.goStacked("CREATE FUNCTION %s RETURNS %s SONAME '%s.%s'" % (
udf, ret, self.udfSharedLibName, self.udfSharedLibExt))
self.createdUdf.add(udf) self.createdUdf.add(udf)
else: else:

View File

@ -40,7 +40,8 @@ class Connector(GenericConnector):
self.password = utf8encode(self.password) self.password = utf8encode(self.password)
try: try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA) self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password,
mode=cx_Oracle.SYSDBA)
logger.info("successfully connected as SYSDBA") logger.info("successfully connected as SYSDBA")
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError), _: except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError), _:
try: try:

View File

@ -5,20 +5,10 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend, getLimitRange, isAdminFromPrivileges, isInferenceAvailable, isNoneValue,\
from lib.core.common import getLimitRange isNumPosStrValue, isTechniqueAvailable
from lib.core.common import isAdminFromPrivileges from lib.core.data import conf, kb, logger, queries
from lib.core.common import isInferenceAvailable from lib.core.enums import CHARSET_TYPE, EXPECTED, PAYLOAD
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.core.exception import sqlmapNoneDataException
from lib.request import inject from lib.request import inject
from plugins.generic.enumeration import Enumeration as GenericEnumeration from plugins.generic.enumeration import Enumeration as GenericEnumeration
@ -41,7 +31,8 @@ class Enumeration(GenericEnumeration):
# Set containing the list of DBMS administrators # Set containing the list of DBMS administrators
areAdmins = set() areAdmins = set()
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if any(isTechniqueAvailable(_) for _ in (
PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
if query2: if query2:
query = rootQuery.inband.query2 query = rootQuery.inband.query2
condition = rootQuery.inband.condition2 condition = rootQuery.inband.condition2
@ -119,7 +110,8 @@ class Enumeration(GenericEnumeration):
query = rootQuery.blind.count2 % queryUser query = rootQuery.blind.count2 % queryUser
else: else:
query = rootQuery.blind.count % queryUser query = rootQuery.blind.count % queryUser
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT,
charsetType=CHARSET_TYPE.DIGITS)
if not isNumPosStrValue(count): if not isNumPosStrValue(count):
if count != 0 and not query2: if count != 0 and not query2:
@ -164,4 +156,4 @@ class Enumeration(GenericEnumeration):
errMsg += "for the database users" errMsg += "for the database users"
raise sqlmapNoneDataException, errMsg raise sqlmapNoneDataException, errMsg
return ( kb.data.cachedUsersRoles, areAdmins ) return kb.data.cachedUsersRoles, areAdmins

View File

@ -7,11 +7,8 @@ See the file 'doc/COPYING' for copying permission
import re import re
from lib.core.common import Backend from lib.core.common import Backend, Format
from lib.core.common import Format from lib.core.data import conf, kb, logger
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 DBMS
from lib.core.session import setDbms from lib.core.session import setDbms
from lib.core.settings import ORACLE_ALIASES from lib.core.settings import ORACLE_ALIASES

View File

@ -10,7 +10,7 @@ try:
import psycopg2.extensions import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
except ImportError, _: except ImportError:
pass pass
from lib.core.data import logger from lib.core.data import logger

View File

@ -8,8 +8,7 @@ See the file 'doc/COPYING' for copying permission
import os import os
from lib.core.common import randomInt from lib.core.common import randomInt
from lib.core.data import kb from lib.core.data import kb, logger
from lib.core.data import logger
from lib.core.exception import sqlmapUnsupportedFeatureException from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.request import inject from lib.request import inject
from plugins.generic.filesystem import Filesystem as GenericFilesystem from plugins.generic.filesystem import Filesystem as GenericFilesystem

View File

@ -5,18 +5,11 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend, Format, getUnicode, randomInt
from lib.core.common import Format from lib.core.data import conf, kb, logger
from lib.core.common import getUnicode from lib.core.enums import DBMS, OS
from lib.core.common import randomInt
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.session import setDbms
from lib.core.settings import PGSQL_ALIASES from lib.core.settings import PGSQL_ALIASES, PGSQL_SYSTEM_DBS
from lib.core.settings import PGSQL_SYSTEM_DBS
from lib.request import inject from lib.request import inject
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint from plugins.generic.fingerprint import Fingerprint as GenericFingerprint

View File

@ -7,9 +7,7 @@ See the file 'doc/COPYING' for copying permission
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.common import randomStr from lib.core.common import randomStr
from lib.core.data import kb from lib.core.data import kb, logger, paths
from lib.core.data import logger
from lib.core.data import paths
from lib.core.enums import OS from lib.core.enums import OS
from lib.core.exception import sqlmapUnsupportedFeatureException from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.request import inject from lib.request import inject

View File

@ -7,16 +7,14 @@ See the file 'doc/COPYING' for copying permission
try: try:
import sqlite3 import sqlite3
except ImportError, _: except ImportError:
pass pass
import logging import logging
from lib.core.convert import utf8encode from lib.core.convert import utf8encode
from lib.core.data import conf from lib.core.data import conf, logger
from lib.core.data import logger from lib.core.exception import sqlmapConnectionException, sqlmapMissingDependence
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapMissingDependence
from plugins.generic.connector import Connector as GenericConnector from plugins.generic.connector import Connector as GenericConnector

View File

@ -5,15 +5,11 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend, Format
from lib.core.common import Format from lib.core.data import conf, kb, logger
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 DBMS
from lib.core.session import setDbms from lib.core.session import setDbms
from lib.core.settings import METADB_SUFFIX from lib.core.settings import METADB_SUFFIX, SQLITE_ALIASES
from lib.core.settings import SQLITE_ALIASES
from lib.request import inject from lib.request import inject
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint from plugins.generic.fingerprint import Fingerprint as GenericFingerprint

View File

@ -40,7 +40,8 @@ class Connector(GenericConnector):
self.initConnection() self.initConnection()
try: 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) 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.OperationalError, msg: except pymssql.OperationalError, msg:
raise sqlmapConnectionException, msg raise sqlmapConnectionException, msg

View File

@ -5,20 +5,11 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission See the file 'doc/COPYING' for copying permission
""" """
from lib.core.common import Backend from lib.core.common import Backend, filterPairValues, isTechniqueAvailable, randomStr, safeSQLIdentificatorNaming, unsafeSQLIdentificatorNaming
from lib.core.common import filterPairValues from lib.core.data import conf, kb, logger, queries
from lib.core.common import isTechniqueAvailable
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.dicts import SYBASE_TYPES from lib.core.dicts import SYBASE_TYPES
from lib.core.enums import PAYLOAD from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapMissingMandatoryOptionException from lib.core.exception import sqlmapMissingMandatoryOptionException, sqlmapNoneDataException
from lib.core.exception import sqlmapNoneDataException
from lib.core.settings import CURRENT_DB from lib.core.settings import CURRENT_DB
from lib.utils.pivotdumptable import pivotDumpTable from lib.utils.pivotdumptable import pivotDumpTable
from plugins.generic.enumeration import Enumeration as GenericEnumeration from plugins.generic.enumeration import Enumeration as GenericEnumeration

Some files were not shown because too many files have changed in this diff Show More