Exemplo n.º 1
0
def tamper(payload, **kwargs):
    """
    Replaces each (MySQL) 0x<hex> encoded string with equivalent CONCAT(CHAR(),...) counterpart

    Requirement:
        * MySQL

    Tested against:
        * MySQL 4, 5.0 and 5.5

    Notes:
        * Useful in cases when web application does the upper casing

    >>> tamper('SELECT 0xdeadbeef')
    'SELECT CONCAT(CHAR(222),CHAR(173),CHAR(190),CHAR(239))'
    """

    retVal = payload

    if payload:
        for match in re.finditer(r"\b0x([0-9a-f]+)\b", retVal):
            if len(match.group(1)) > 2:
                result = "CONCAT(%s)" % ','.join(
                    "CHAR(%d)" % _ for _ in getOrds(decodeHex(match.group(1))))
            else:
                result = "CHAR(%d)" % ord(decodeHex(match.group(1)))
            retVal = retVal.replace(match.group(0), result)

    return retVal
Exemplo n.º 2
0
def oracle_old_passwd(password,
                      username,
                      uppercase=True):  # prior to version '11g'
    """
    Reference(s):
        http://www.notesbit.com/index.php/scripts-oracle/oracle-11g-new-password-algorithm-is-revealed-by-seclistsorg/

    >>> oracle_old_passwd(password='******', username='******', uppercase=True)
    'F894844C34402B67'
    """

    IV, pad = "\0" * 8, "\0"

    unistr = b"".join((b"\0" + _.encode(UNICODE_ENCODING)
                       ) if ord(_) < 256 else _.encode(UNICODE_ENCODING)
                      for _ in (username + password).upper())

    cipher = des(decodeHex("0123456789ABCDEF"), CBC, IV, pad)
    encrypted = cipher.encrypt(unistr)
    cipher = des(encrypted[-8:], CBC, IV, pad)
    encrypted = cipher.encrypt(unistr)

    retVal = encodeHex(encrypted[-8:], binary=False)

    return retVal.upper() if uppercase else retVal.lower()
Exemplo n.º 3
0
def _formatPartialContent(value):
    """
    Prepares (possibly hex-encoded) partial content for safe console output
    """

    if value and isinstance(value, six.string_types):
        try:
            value = decodeHex(value, binary=False)
        except:
            pass
        finally:
            value = safecharencode(value)

    return value
Exemplo n.º 4
0
def mssql_new_passwd(password, salt, uppercase=False):
    """
    Reference(s):
        http://hashcat.net/forum/thread-1474.html

    >>> mssql_new_passwd(password='******', salt='4086ceb6', uppercase=False)
    '0x02004086ceb6eb051cdbc5bdae68ffc66c918d4977e592f6bdfc2b444a7214f71fa31c35902c5b7ae773ed5f4c50676d329120ace32ee6bc81c24f70711eb0fc6400e85ebf25'
    """

    binsalt = decodeHex(salt)
    unistr = b"".join(b"%s\0" % _.encode(UNICODE_ENCODING) if ord(_) < 256 else _.encode(UNICODE_ENCODING) for _ in password)

    retVal = "0200%s%s" % (salt, sha512(unistr + binsalt).hexdigest())

    return "0x%s" % (retVal.upper() if uppercase else retVal.lower())
Exemplo n.º 5
0
def mssql_passwd(password, salt, uppercase=False):
    """
    Reference(s):
        http://www.leidecker.info/projects/phrasendrescher/mssql.c
        https://www.evilfingers.com/tools/GSAuditor.php

    >>> mssql_passwd(password='******', salt='4086ceb6', uppercase=False)
    '0x01004086ceb60c90646a8ab9889fe3ed8e5c150b5460ece8425a'
    """

    binsalt = decodeHex(salt)
    unistr = b"".join(b"%s\0" % _.encode(UNICODE_ENCODING) if ord(_) < 256 else _.encode(UNICODE_ENCODING) for _ in password)

    retVal = "0100%s%s" % (salt, sha1(unistr + binsalt).hexdigest())

    return "0x%s" % (retVal.upper() if uppercase else retVal.lower())
Exemplo n.º 6
0
def oracle_passwd(password, salt, uppercase=True):
    """
    Reference(s):
        https://www.evilfingers.com/tools/GSAuditor.php
        http://www.notesbit.com/index.php/scripts-oracle/oracle-11g-new-password-algorithm-is-revealed-by-seclistsorg/
        http://seclists.org/bugtraq/2007/Sep/304

    >>> oracle_passwd(password='******', salt='1B7B5F82B7235E9E182C', uppercase=True)
    'S:2BFCFDF5895014EE9BB2B9BA067B01E0389BB5711B7B5F82B7235E9E182C'
    """

    binsalt = decodeHex(salt)
    password = getBytes(password)

    retVal = "s:%s%s" % (sha1(password + binsalt).hexdigest(), salt)

    return retVal.upper() if uppercase else retVal.lower()
Exemplo n.º 7
0
def mssql_old_passwd(password, salt, uppercase=True):  # prior to version '2005'
    """
    Reference(s):
        www.exploit-db.com/download_pdf/15537/
        http://www.leidecker.info/projects/phrasendrescher/mssql.c
        https://www.evilfingers.com/tools/GSAuditor.php

    >>> mssql_old_passwd(password='******', salt='4086ceb6', uppercase=True)
    '0x01004086CEB60C90646A8AB9889FE3ED8E5C150B5460ECE8425AC7BB7255C0C81D79AA5D0E93D4BB077FB9A51DA0'
    """

    binsalt = decodeHex(salt)
    unistr = b"".join(b"%s\0" % _.encode(UNICODE_ENCODING) if ord(_) < 256 else _.encode(UNICODE_ENCODING) for _ in password)

    retVal = "0100%s%s%s" % (salt, sha1(unistr + binsalt).hexdigest(), sha1(unistr.upper() + binsalt).hexdigest())

    return "0x%s" % (retVal.upper() if uppercase else retVal.lower())
Exemplo n.º 8
0
def decodePage(page, contentEncoding, contentType, percentDecode=True):
    """
    Decode compressed/charset HTTP response

    >>> getText(decodePage(b"<html>foo&amp;bar</html>", None, "text/html; charset=utf-8"))
    '<html>foo&bar</html>'
    """

    if not page or (conf.nullConnection and len(page) < 2):
        return getUnicode(page)

    if hasattr(contentEncoding, "lower"):
        contentEncoding = contentEncoding.lower()
    else:
        contentEncoding = ""

    if hasattr(contentType, "lower"):
        contentType = contentType.lower()
    else:
        contentType = ""

    if contentEncoding in ("gzip", "x-gzip", "deflate"):
        if not kb.pageCompress:
            return None

        try:
            if contentEncoding == "deflate":
                data = io.BytesIO(
                    zlib.decompress(page, -15)
                )  # Reference: http://stackoverflow.com/questions/1089662/python-inflate-and-deflate-implementations
            else:
                data = gzip.GzipFile("", "rb", 9, io.BytesIO(page))
                size = struct.unpack(
                    "<l", page[-4:]
                )[0]  # Reference: http://pydoc.org/get.cgi/usr/local/lib/python2.5/gzip.py
                if size > MAX_CONNECTION_TOTAL_SIZE:
                    raise Exception("size too large")

            page = data.read()
        except Exception as ex:
            if "<html" not in page:  # in some cases, invalid "Content-Encoding" appears for plain HTML (should be ignored)
                errMsg = "detected invalid data for declared content "
                errMsg += "encoding '%s' ('%s')" % (contentEncoding,
                                                    getSafeExString(ex))
                singleTimeLogMessage(errMsg, logging.ERROR)

                warnMsg = "turning off page compression"
                singleTimeWarnMessage(warnMsg)

                kb.pageCompress = False
                raise SqlmapCompressionException

    if not conf.encoding:
        httpCharset, metaCharset = None, None

        # Reference: http://stackoverflow.com/questions/1020892/python-urllib2-read-to-unicode
        if contentType.find("charset=") != -1:
            httpCharset = checkCharEncoding(contentType.split("charset=")[-1])

        metaCharset = checkCharEncoding(
            extractRegexResult(META_CHARSET_REGEX, page))

        if (any((httpCharset, metaCharset)) and not all(
            (httpCharset, metaCharset))) or (httpCharset == metaCharset
                                             and all(
                                                 (httpCharset, metaCharset))):
            kb.pageEncoding = httpCharset or metaCharset  # Reference: http://bytes.com/topic/html-css/answers/154758-http-equiv-vs-true-header-has-precedence
            debugMsg = "declared web page charset '%s'" % kb.pageEncoding
            singleTimeLogMessage(debugMsg, logging.DEBUG, debugMsg)
        else:
            kb.pageEncoding = None
    else:
        kb.pageEncoding = conf.encoding

    # can't do for all responses because we need to support binary files too
    if isinstance(page, six.binary_type) and "text/" in contentType:
        # e.g. &#x9;&#195;&#235;&#224;&#226;&#224;
        if b"&#" in page:
            page = re.sub(
                b"&#x([0-9a-f]{1,2});", lambda _: decodeHex(
                    _.group(1)
                    if len(_.group(1)) == 2 else "0%s" % _.group(1)), page)
            page = re.sub(
                b"&#(\\d{1,3});", lambda _: six.int2byte(int(_.group(1)))
                if int(_.group(1)) < 256 else _.group(0), page)

        # e.g. %20%28%29
        if percentDecode:
            if b"%" in page:
                page = re.sub(b"%([0-9a-fA-F]{2})",
                              lambda _: decodeHex(_.group(1)), page)

        # e.g. &amp;
        page = re.sub(
            b"&([^;]+);",
            lambda _: six.int2byte(HTML_ENTITIES[getText(_.group(1))])
            if HTML_ENTITIES.get(getText(_.group(1)), 256) < 256 else _.group(
                0), page)

        kb.pageEncoding = kb.pageEncoding or checkCharEncoding(
            getHeuristicCharEncoding(page))

        if (kb.pageEncoding or "").lower() == "utf-8-sig":
            kb.pageEncoding = "utf-8"
            if page and page.startswith(
                    "\xef\xbb\xbf"
            ):  # Reference: https://docs.python.org/2/library/codecs.html (Note: noticed problems when "utf-8-sig" is left to Python for handling)
                page = page[3:]

        page = getUnicode(page, kb.pageEncoding)

        # e.g. &#8217;&#8230;&#8482;
        if "&#" in page:

            def _(match):
                retVal = match.group(0)
                try:
                    retVal = _unichr(int(match.group(1)))
                except (ValueError, OverflowError):
                    pass
                return retVal

            page = re.sub(r"&#(\d+);", _, page)

        # e.g. &zeta;
        page = re.sub(
            r"&([^;]+);", lambda _: _unichr(HTML_ENTITIES[_.group(1)])
            if HTML_ENTITIES.get(_.group(1), 0) > 255 else _.group(0), page)

    return page