#!/usr/bin/env python3

"""
verbal.py 0.1 - HTTP(S) Request Method Security Scanner
Copyright (c) 2017 Marco Ivaldi <raptor@0xdeadbeef.info>

"The Other Way to Pen-Test" --HD Moore & Valsmith

Verbal is a HTTP request method security scanner. It
tries a series of interesting HTTP methods against a
list of website paths, in order to determine which
methods are available and accessible. The following
HTTP methods are currently supported (HEAD and POST
aren't that interesting, while DELETE and PATCH would
be too dangerous to blindly try as part of an automated
scan):

GET: request a representation of a resource
OPTIONS: get communication options for a resource
TRACE: perform a message loop-back test
DEBUG: start/stop remote debugging session on IIS
PUT: replace a resource with the request payload

Requirements:
Python 3 (https://pythonclock.org/ is ticking...)
Requests (http://docs.python-requests.org/)

Example usage:
$ ./verbal.py -A -u http://example.com -d directories.txt

TODO:
Test thoroughly, especially the PUT scanner
Introduce spidering capabilities and IP address scanning
Implement support for additional methods (e.g. CONNECT)

Get the latest version at:
https://github.com/0xdea/tactical-exploitation/
"""

VERSION = "0.1"
BANNER = """
verbal.py {0} - HTTP(S) Request Method Security Scanner
Copyright (c) 2017 Marco Ivaldi <raptor@0xdeadbeef.info>
""".format(VERSION)

import sys
import argparse
import re
import requests

# disable InsecureRequestWarning
import urllib3
urllib3.disable_warnings()

def http_method_scanner(args):
    """
    Generic HTTP request method scanner
    """

    base = args.u.rstrip("/")
    timeout = args.t

    dirs = set()
    if args.d:
        dirs = {d.rstrip().strip("/") + "/" for d in args.d}
    dirs.add("")

    if args.all: # activate all additional scanners
        args.trace = True
        args.debug = True
        args.put = True

    print("*** Scanning {0} ***\n".format(base))

    for d in sorted(dirs):

        url = base + "/" + d
        print(url)

        # base scanners
        scan_get(url, timeout)
        scan_options(url, timeout)

        # additional scanners
        if args.trace:
            scan_trace(url, timeout)
        if args.debug:
            scan_debug(url, timeout)
        if args.put:
            scan_put(url, timeout)

        print("")

    print("*** Finished {0} ***\n".format(base))

def scan_get(url, timeout):
    """
    GET method and Directory Listing scanner
    """

    try:
        r = requests.get(
                url=url,
                timeout=timeout,
                verify=False)
        print(
                "    GET" + "\t\t> "
                + str(r.status_code) + " ("
                + str(requests.status_codes._codes[r.status_code][0]) + ")")

    except (KeyboardInterrupt, SystemExit):
        sys.exit(1)

    except Exception as err:
        print("\n// error: {0}".format(err))
        sys.exit(1) # exit in case of error

    else: # bonus check;)
        p = re.compile("(Index of )|(To Parent Directory)") # apache, iis
        if p.search(r.text):
            print("        Directory Listing is enabled")

def scan_options(url, timeout):
    """
    OPTIONS method scanner
    """

    try:
        r = requests.options(
                url=url,
                timeout=timeout,
                verify=False)
        print(
                "    OPTIONS" + "\t> "
                + str(r.status_code) + " ("
                + str(requests.status_codes._codes[r.status_code][0]) + ")")
        print("        " + "Methods: " + r.headers["allow"])

    except (KeyboardInterrupt, SystemExit):
        sys.exit(1)

    except Exception as err:
        pass # ignore errors

def scan_trace(url, timeout):
    """
    TRACE method scanner
    """

    try:
        r = requests.request(
                url=url,
                timeout=timeout,
                verify=False,
                method="TRACE")
        print(
                "    TRACE" + "\t> "
                + str(r.status_code) + " ("
                + str(requests.status_codes._codes[r.status_code][0]) + ")")

    except (KeyboardInterrupt, SystemExit):
        sys.exit(1)

    except Exception as err:
        print("        // error: {0}".format(err))

def scan_debug(url, timeout):
    """
    DEBUG method scanner
    """

    target = url + "verbal.aspx"
    headers = {
            "Accept" : "*/*",
            "Command" : "stop-debug"}

    try:
        r = requests.request(
                url=target,
                timeout=timeout,
                verify=False,
                method="DEBUG",
                headers=headers)
        print(
                "    DEBUG" + "\t> "
                + str(r.status_code) + " ("
                + str(requests.status_codes._codes[r.status_code][0]) + ")")

    except (KeyboardInterrupt, SystemExit):
        sys.exit(1)

    except Exception as err:
        print("        // error: {0}".format(err))

def scan_put(url, timeout): # TODO: test thoroughly
    """
    PUT method scanner
    """

    # interesting file types to check
    filetypes = ["txt", "html", "xml", "js", "php", "asp", "aspx", "jsp"]

    print("    PUT")

    for t in filetypes:
        target = url + "verbal." + t

        try:
            r = requests.put(
                    url=target,
                    timeout=timeout,
                    verify=False,
                    data="PENTEST")
            print(
                    "        " + t + "\t> "
                    + str(r.status_code) + " ("
                    + str(requests.status_codes._codes[r.status_code][0]) + ")")

        except (KeyboardInterrupt, SystemExit):
            sys.exit(1)

        except Exception as err:
            print("        // error: {0}".format(err))

def get_args():
    """
    Get command line arguments
    """

    parser = argparse.ArgumentParser()
    parser.set_defaults(func=http_method_scanner)

    # http methods
    parser.add_argument(
            "-T", "--trace",
            action="store_true",
            help="TRACE method scanner")
    parser.add_argument(
            "-D", "--debug",
            action="store_true",
            help="DEBUG method scanner")
    parser.add_argument(
            "-P", "--put",
            action="store_true",
            help="PUT method scanner")
    parser.add_argument(
            "-A", "--all",
            action="store_true",
            help="Scan all supported methods")

    # targets
    parser.add_argument(
            "-u",
            metavar="BASE_URL",
            required=True,
            help="target base URL")
    parser.add_argument(
            "-d",
            metavar="DIR_FILE",
            type=argparse.FileType("r"),
            help="file containing a list of directories")

    # other arguments
    parser.add_argument(
            "-t",
            metavar="TIMEOUT",
            type=int,
            default=5,
            help="timeout in seconds (default: 5)")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(0)

    return parser.parse_args()

def main():
    """
    Main function
    """

    print(BANNER)

    if sys.version_info[0] != 3:
        print("// error: this script requires python 3")
        sys.exit(1)

    args = get_args()
    args.func(args)

if __name__ == "__main__":
    main()